Explain the basic implementation of TCP and UDP programs and the development of multithreaded concurrent server (Java)

1, What is network programming The so-called network programming is to realize the communication between hosts in the network

1. In the whole communication process, there are generally two kinds of endpoints: server and client
2. There are two modes of program development around the server and client: C/S structure (two sets of programs need to be maintained, which has good security performance) and B/S structure (generally used for browser development, which only needs to maintain the server. Such programs use public ports, including public protocols, so the security performance is very poor)
3. Two popular implementations of C/S structure programs: TCP model and UDP model
4. So what is HTTP? Is it related to TCP communication In fact, HTTP communication is also an application based on TCP protocol, which is formed after adding some HTTP standards to the protocol. It is mainly used in B/S structure and some distributed development

2, Echo program model?: The client enters a message through the keyboard. After sending this message to the server, the server will feed back this message to the client for display

The implementation of Echo program model is mainly through Java Net package:
1.Server Socket class: encapsulates TCP protocol class and works on the server side.
2.Socket class: an operation class that encapsulates the TCP protocol. Each socket object represents a client

Server side:

//Define Echo server side
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EchoServer{
 	public static void main(String[] args)throws Exception{
 		 ServerSocket server = new ServerSocket(9999);//Set the port number of service listening
  		 System.out.println("Waiting for client connection...........");
  		 Socket client = server.accept();//Waiting for client connection
  		 /First, you need to receive the information sent by the client, and then you can process the information and send it back to the client
   		 Scanner scan = new Scanner(client.getInputStream());
    		 scan.useDelimiter("\n");
  		 PrintStream out = new PrintStream(client.getOutputStream());
        	 boolean flag = true;
  		 while(flag){
   			if(scan.hasNext()){
    				String val = scan.next().trim();
    				if("byebye".equalsIgnoreCase(val)){
     				out.println("ByeByeBye...");
     				flag = false;
    				}else{
     				out.println("[ECHO}" + val);
   			    }
   		 	 }
  		 }
  		 scan.close();
        	 out.close();
    		 client.close();
  		 server.close();
 	}
}

Program execution results:

This program instantiates a Server Socket class object in the main thread, and it is set to listen on the 9999 port of this machine. When a client connects to the server (the accept() method will block the program execution before the client connects), it will obtain the input stream and output stream of the client Socket for receiving and responding.
The main function of the server is to echo the data sent by the client, and the client needs to input the data from the keyboard, and send and respond the data through the Socket instance.

client:

//Writing client programs
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class EchoClient{
	private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(
		new InputStreamReader(System.in));
	public static String getString(String prompt) throws Exception{//Keyboard information input
		System.out.print(prompt);
		String str = KEYBOARD_INPUT.readLine();
		return str;
	}
	public static void main(String prompt) throws Exception{
		Socket client = new Socket("localhost",9999);//Define the connection information of the server
		Scanner scan = new Scanner(client.getInputStream());//Receive service input
		scan.useDelimiter("\n");
		PrintStream out = new PrintStream(client.getOutputStream());//Send content to server
		boolean flag = true;
		while(flag){
			String input = getString("Please enter the content to send:").trim();
			out.println(input);
			if(scan.hasNext()){
				System.out.println(scan.next());
			}
			if("byebye".equalsIgnoreCase(input)){
				flag = false;
			}
		}
		scan.close();
		out.close();
		client.close();
	}
}

Program execution results:

3, BIO processing model?: In short, BIO processing model (non-traditional blocking IO model) is used to realize multi-user access

BIO processing model means that multi threads can be used to process the communication needs of multiple clients. Compared with the network communication realized by the processing mechanism of Echo model based on single thread, the processing performance of BIO processing model server is higher

//Service end of BIO processing model
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class BioServer{
	private static class ClientThread implements Runnable{//Client thread class
		private Socket client = null;//Client Socket        
		private Scanner scan  = null;//Input stream        
		private PrintStream out = null;//Output stream        
		private boolean flag = true;//Cyclic marking        
		public ClientThread(Socket client) throws Exception{//Receive the socket of the client            
			this.client = client;//Save basket            
			this.scan = new Scanner(client.getInputStream());//Input stream            
			this.scan.useDelimiter("\n");//Set separator            
			this.out = new PrintStream(client.getOutputStream());//Output stream        
		}
		public void run(){//Thread execution           
			while(this.flag){//Echo loop processing                
	 			if(scan.hasNext()){//Data transmission                    
	 				String val = scan.next().trim();//receive data                     
	 				if("byebye".equalsIgnoreCase(val)){//End response                        
	 					out.println("ByeBYeBye....");//Response information                        
	 					this.flag = false;//End cycle                    
	 				}else{                        
						out.println("[BIO]" + val);//Echo message                    
					}                
	 			}            
	 	  }
	 	  try{                
	 	  	scan.close();//Close input stream                
	 	  	out.close();//Close output stream                
	 	  	client.close();//Close client            
	 	  }catch(IOException e){                
	 	  	e.printStackTrace();            
		  }        
	  }   
    }
    public static void main(String[] args) throws Exception{        
    	ServerSocket server = new ServerSocket(9999);//Set service listening port        
    	System.out.println("Waiting for client connection...........");//Print prompt information        
    	boolean flag = true ;//Cyclic marking        
    	while(flag){//There is a client connection            
    		Socket client = server.accept();            
    		new Thread(new ClientThread(client)).start();        
    	}        
    	server.close();//Turn off the server side    
    }
}

The server of this program realizes the connection of multiple Socket clients in the form of loop, and each received Socket instance is encapsulated into an independent thread for independent Echo response processing This means that the number of threads available on the server side will not increase in the development of the server side, but this means that the number of threads available on the server side will not increase seriously.

4, UDP program?: First of all, why use UDP? All operations of TCP must establish a reliable connection to communicate, but this method will waste a lot of system performance. In order to reduce this overhead, UDP is also called unreliable connection, that is, data transmission in the form of datagram

Network program developed using UDP. Similar to the normal use of mobile phones, the mobile phone is actually equivalent to a client. If the current mobile phone wants to receive information normally, the mobile phone must be turned on first.

client:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPClient{
	public static void main(String[] args)throws Exception{//Receive data information
		DatagramSocket client = new DatagramSocket(9999);//9999 port listening
		byte data[] = new byte[1024];//Save the received data information
		DatagramPacket packet = new DatagramPacket(data,data.length);//Create data link report
		System.out.println("The client is waiting to receive the sent letter.........");//Prompt information
		client.receive(packet);//Receive message content
		System.out.println("The received message contents are:" + new String(data,0,packet.getLength()));
		client.close();//Close connection
	}
}	

Program execution results:

When writing a UDP client, you need to set a listening port of the client. The received data information can be received using datagram packet class objects. In this way, when the client is opened, the message sent by the server will be automatically received

Server:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer{
	public static void main(String[] args)throws Exception{
		DatagramSocket server = new DatagramSocket(9000);
		String str = "hello";
		DatagramPacket packet = new DatagramPacket(str.getBytes(),0,str.length(),
			InetAddress.getByName("localhost"),9999);//send data
		server.send(packet);//send message
		System.out.println("Message sent....");
		server.close();//Turn off the server side
	}
}	

Program execution results:

This program sets the content of datagram to be sent through datagram packet, and also sets the host name and listening port received by the client. For the server, it only cares about whether the message is sent, not whether the client has received the message

5, Summary:

1.TCP is the basis of HTTP communication. Reliable data transmission services can be realized by using TCP. In Java, the TCP protocol is encapsulated through ServerSocket and Socket.
2.ServerSocket is mainly used for the creation of the server, and the listening port of the server can be defined.
3. In order to improve the concurrency performance of the server, the multi-threaded mode can be adopted, and if the multi-threaded mode is used, the waiting and wake-up mechanism of the client connection must be added. This kind of program model is called BIO.
4.UDP is a datagram transmission protocol, and the client may not receive the message content sent by the server

Tags: Java Multithreading Network Communications

Posted by coolfool on Mon, 11 Apr 2022 19:35:01 +0300