Java Socket server client communication example

1. What is Socket

It is actually a model object encapsulated by Java for TCP communication.

TCP communication is divided into server and client. Java language provides ServerSocket and Socket classes for this.

2. Operating mechanism

The server runs on a certain port of a machine, waiting for the client to access.

The client initiates access to the specified port of the specified IP machine.

When the server receives the client's access request, it will establish a Socket to represent the client, and perform input and output operations through the Socket.

After the client has established a connection with the server, there will also be a Socket for input and output operations.

3. Code example

First, establish a server and wait for client connections on port 10000.

/**
 * Hello服务端
 */
public class HelloServerSocket {
    
    
	public static void main(String[] args) throws IOException {
    
    
		// 服务端Socket
		ServerSocket serverSocket = new ServerSocket(10000);
		// 一直运行,等待客户端请求
		while (true) {
    
    
			// 每当收到客户端请求,则生成一个对应的客户端Socket
			Socket socket = serverSocket.accept();
			// 对客户端输出Hello
			PrintStream stream = new PrintStream(socket.getOutputStream());
			stream.print("Hello");
			// 关闭输出流和客户端
			stream.close();
			socket.close();
		}
	}
}

Then initiate an access request through the client:

/**
 * Hello客户端
 */
public class HelloClientSocket {
    
    
	public static void main(String[] args) throws UnknownHostException, IOException {
    
    
		// 指定服务端IP和端口
		Socket socket = new Socket("127.0.0.1", 10000);
		// 获取输入流,此处包装了下,通过BufferedReader读取服务端输入内容
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String line = null;
		while ((line = reader.readLine()) != null) {
    
    
			System.out.println("来自服务端的问候:" + line);
		}
	}
}

4. Testing

Run the server first, then run the client, each time the client console is run, it will print:

来自服务端的问候:Hello

5. Summary

This is one of the simplest Socket communication programs. It can be found that the Java encapsulation is quite in place.

Guess you like

Origin blog.csdn.net/woshisangsang/article/details/107717508