1. Three elements of network programming
1.IP address
The address of a device on the network is its unique identifier.
2.Port
The unique identifier of the application on the device.
3. Agreement
The rules for data transmission in the network. Common protocols include UDP protocol and TCP protocol.
2.IP
IP: The full name is “Internet Protocol Address”, also known as IP address. It is a digital label assigned to an Internet-connected device. Common IP classifications are: ipv4 and ipv6
IPv6: Due to the booming development of the Internet, the demand for IP addresses is increasing, and the total number of IPs under the IPv4 model is limited. Using 128-bit address length, divided into 8 groups.
Usage of InetAddress
In order to facilitate our acquisition and operation of IP addresses, Java provides a class InetAddress for us to use InetAddress: This class represents the Internet Protocol (IP) address
3.Port
Port: The unique identification of the application in the device.
Port number: an integer represented by two bytes, its value range is 0~65535. The port numbers between 0 and 1023 are used for some well-known network services or applications. We can just use a port number above 1024. Note: A port number can only be used by one application.
4. Agreement
Protocol: In computer networks, the rules for connection and communication are called network communication protocols.
UDP protocol
1.User Datagram Protocol
2.UDP is a connectionless communication protocol. The speed is fast, there is a size limit and a maximum of 64K can be sent at one time. The data is not secure and data is easily lost.
TCP protocol
1. Transmission Control Protocol
2. TCP protocol is a connection-oriented communication protocol. Slow speed, no size limit, data security.
5.UDP communication
General steps
UDP sender steps
1. Create the DatagramSocket object of the sending end
2. Create data and package the data (DatagramPacket)
3. Call the method of DatagramSocket object to send data
4. Release resources
UDP receiver steps
1. Create the DatagramSocket object of the receiving end
2. Create a box to receive data
3. Call the DatagramSocket method to receive the data and put the data into the box
4. Parse the data packet and display the data on the console
5. Release resources
6.UDP communication—unicast
Client code:
public class ClientDemo { private static String host = "127.0.0.1"; private static int port = 10000; private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { DatagramSocket ds = null; String msg; try { ds = new DatagramSocket(); // Create connection object do { System.out.println("Please enter the message to be sent"); msg = sc.nextLine(); byte[] bytes = msg.getBytes(StandardCharsets.UTF_8); DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(host), port); // Create a package and specify the ip address and port number ds.send(dp); // Send data } while (!"886".equals(msg)); }catch (Exception e){ e.printStackTrace(); }finally { ds.close(); } } }
Server code:
public class ServerDemo { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(10000); //Specify the listening port number byte[] bytes = new byte[1024]; DatagramPacket dp = new DatagramPacket(bytes, bytes.length); while (true) { ds.receive(dp); //If there is no sender to connect here, it will be blocked here and wait. int length = dp.getLength(); byte[] data = dp.getData(); String msg = new String(data, 0, length); if("886".equals(msg)){ System.out.println("receiving end stop"); ds.close(); break; } System.out.println("Receiver: " + msg); } } }
7.UDP communication—Multicast
Multicast address: 224.0.0.0 ~ 239.255.255.255 Among them, 224.0.0.0 ~ 224.0.0.255 is the reserved multicast address
client code
public class clientDemo { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(); byte[] bytes = "Hello, I am xxx".getBytes(StandardCharsets.UTF_8); InetAddress address = InetAddress.getByName("224.0.1.0"); // Create a multicast address int port = 10000; DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port); //Create a package to brake the multicast address and port number ds.send(dp); // send ds.close(); } }
Server 1 code
public class ServerDemo1 { public static void main(String[] args) throws IOException { MulticastSocket ms = new MulticastSocket(10000); //Define the multicast communication object and specify the port number DatagramPacket dp = new DatagramPacket(new byte[1024], 1024); ms.joinGroup(InetAddress.getByName("224.0.1.0")); // Add this machine to the multicast ms.receive(dp); byte[] data = dp.getData(); int length = dp.getLength(); System.out.println("Receiver 1:"); System.out.println(new String(data, 0, length)); } }
Server 2 code
public class ServerDemo2 { public static void main(String[] args) throws IOException { MulticastSocket ms = new MulticastSocket(10000); //Define the multicast communication object and specify the port number DatagramPacket dp = new DatagramPacket(new byte[1024], 1024); ms.joinGroup(InetAddress.getByName("224.0.1.0")); // Add this machine to the multicast ms.receive(dp); byte[] data = dp.getData(); int length = dp.getLength(); System.out.println("Receiver 2:"); System.out.println(new String(data, 0, length)); } }
8.UDP communication—broadcast
Broadcast address: 255.255.255.255
client code
public class clientDemo { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(); byte[] bytes = "Hello, I am xxx".getBytes(StandardCharsets.UTF_8); InetAddress address = InetAddress.getByName("255.255.255.255"); // Specify 255.255.255.255 to indicate that it is a broadcast address int port = 10000; DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port); // Create a package ds.send(dp); ds.close(); } }
Server code
//Multicast code public class ServerDemo1 { public static void main(String[] args) throws IOException { MulticastSocket ms = new MulticastSocket(10000); // Create a multicast connection object DatagramPacket dp = new DatagramPacket(new byte[1024], 1024); // Create package ms.joinGroup(InetAddress.getByName("224.0.1.0")); // Add this machine to the multicast ms.receive(dp); byte[] data = dp.getData(); int length = dp.getLength(); System.out.println("Receiver 1:"); System.out.println(new String(data, 0, length)); } } //Multicast code public class ServerDemo1 { public static void main(String[] args) throws IOException { MulticastSocket ms = new MulticastSocket(10000); // Create a multicast connection object DatagramPacket dp = new DatagramPacket(new byte[1024], 1024); // Create package ms.joinGroup(InetAddress.getByName("224.0.1.0")); // Add this machine to the multicast ms.receive(dp); byte[] data = dp.getData(); int length = dp.getLength(); System.out.println("Receiver 2:"); System.out.println(new String(data, 0, length)); } } //Note: Multicast and unicast cannot monitor the same port at the same time //Unicast code public class ServerDemo3 { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(10000); // Create a unicast connection object DatagramPacket dp = new DatagramPacket(new byte[1024], 1024); // Create package ds.receive(dp); byte[] data = dp.getData(); int length = dp.getLength(); System.out.println("Unicast receiving end:"); System.out.println(new String(data, 0, length)); } }
9.TCP communication
TCP communication protocol is a reliable network protocol that establishes a Socket object at both ends of the communication.
Before communicating, make sure the connection has been established.
Generate IO streams through Socket for network communication.
TCP steps to send data
Steps to send data
① Create the client’s Socket object (Socket) to connect to the specified server
Socket(String host, int port)
② Get the output stream and write data
OutputStream getOutputStream()
③ Release resources
void close()
TCP receives data steps to receive data
Steps to receive data
① Create a server-side Socket object (ServerSocket)
ServerSocket(int port)
② Monitor the client connection and return a Socket object
Socket accept()
③ Get the input stream, read the data, and display the data on the console
InputStream getInputStream()
④ Release resources
void close()
10.TCP three-way handshake
11.TCP wave four times
12.TCP communication—code
client code
public class ClientSocket { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1", 10000);//Create a socket object and specify the sending IP address and port number OutputStream os = socket.getOutputStream(); // Get the output stream and output the array to the network channel os.write("hello".getBytes()); socket.shutdownOutput(); // Sending the end flag indicates that the client has completed sending (if it is not declared, the server will not be able to obtain the stop flag, which means that the server will always loop in this thread) InputStream inputStream = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String s; while ((s = br.readLine()) != null){ System.out.println(s); } os.close(); br.close(); socket.close(); } }
Server code
public class ServerSocketDemo { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10000); // Create a tcp connection and specify the listening port Socket accept = ss.accept(); // Accept client data. If there is no connection, it will wait until it is blocked. InputStream is = accept.getInputStream(); int b; while ((b = is.read()) != -1){ System.out.print((char) b); // Get the client’s data and print it } OutputStream os = accept.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); // Return data to the client bw.write("Who are you?"); bw.newLine(); bw.flush(); is.close(); bw.close(); ss.close(); } }
13.TCP realizes image upload (multi-thread upload)
Require:
Client: Upload local files to the server. Receive feedback from the server.
Server: Receives files uploaded by the client and gives feedback after the upload is completed.
client code
public class clientDemo { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1", 10000); // Create a socket object and specify the sending IP address and port number BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src/main/resources/a1.jpeg")); // Specify the local array address BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); // Use byte buffer stream to write data with high efficiency int len; byte[] bytes = new byte[1024 * 8]; while ((len = bis.read(bytes)) != -1){ bos.write(bytes, 0, len); } socket.shutdownOutput(); // End flag BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Use conversion stream to convert byte stream into character stream String line; while ((line = br.readLine()) != null){ //Display the palindrome on the server side System.out.println(line); } bis.close(); br.close(); socket.close(); } }
Server code
//Use thread pool to create multiple threads public class serverDemo { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10000); ThreadPoolExecutor pool = new ThreadPoolExecutor( 3,//Number of core threads 10, //Maximum number of threads 60, // The idle time of the temporary thread exceeds how long it will be destroyed TimeUnit.SECONDS, // The unit of idle time of the temporary thread. The unit will be destroyed after the amount of time. new ArrayBlockingQueue<>(5), // Blocking queue can block up to 5 threads Executors.defaultThreadFactory(), //How to create threads new ThreadPoolExecutor.AbortPolicy() // Deny policy ); while (true){ Socket accept = ss.accept(); MyTask myTask = new MyTask(accept); pool.submit(myTask); } } }
thread code
public class MyTask implements Runnable{ private Socket accept; //Define tcp communication object public MyTask(Socket a){ this.accept = a; } @Override public void run() { BufferedOutputStream bos = null; try { InputStream is = accept.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bos = new BufferedOutputStream(new FileOutputStream("src/main/resources/" + UUID.randomUUID().toString() + ".jpeg")); int len; byte[] bytes = new byte[1024]; while ((len = bis.read(bytes)) != -1){ bos.write(bytes, 0,len); } //Reply message to client BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream())); bw.write("Upload completed"); bw.newLine(); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { accept.close(); if(bos != null) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } } }