Design Optimization Scheme of ServerSocket in Java Network Communication

  • 2021-07-18 07:53:14
  • OfStack

In the network communication of java, two hosts of different nodes want to communicate by establishing Socket object (equivalent to client host, which requests to send information to server) and ServerSocket object (equivalent to server host, which receives connection request from client and replies information).

1: Create an Socket object


Socket socket = new Socket("IP",port);

Specify the ip address and port number of the server to be connected to create an Socket object, which can be output and input after creation.

2: Create an ServerSocket object


ServerSocket sever = new ServerSocket(port); // This port is the port that the client connects to 
Socket connnection = server.accept(); // Blocking the port above this listening, 1 But if there is a connection request, it will be processed. 

Creates a new ServerSocket object that blocks the specified port that listens for client connections, 1 but processes new connection requests.

The basic relationship is: Socket-------- > ServerSocket

At this time, as long as one connection server blocks and makes processing, wait until the end of processing, and then reset the monitoring port state. If another one new connection request comes...... 1 straight reciprocating processing action. The obvious disadvantage is that the efficiency is low, only one request can be processed at a time, and it is blocked.

Optimization process:

In BIO, multi-threading is started, and every request server starts one thread processing. (The advantage is efficiency, but the disadvantage is also obvious: The advantage is that a large number of almost simultaneous inbound connections may cause it to generate a very large number of threads. Eventually, the java virtual machine consumes memory 2 and crashes). The above scheme is improved: thread pool is used to manage threads in BIO. It can handle efficiency and prevent the server from crashing due to high concurrent connections. Use NIO. (NIO is also a single thread to process connection requests, but it will not block, and will constantly poll whether there are ready events, so the processing order has nothing to do with the sequence of connection requests, but has something to do with the sequence of request data arrival. The multiplex interface (select) can be called in one thread to block and listen to IO requests from multiple clients at the same time, and the corresponding function can be called once IO requests are received.)

Summarize


Related articles: