Java ServerSocket connection restrictions?
I'm using sockets for some tests. I've encountered some strange behaviors: after the 50th client socket is connected, the ServerSocket will reject the connection, even if the client socket is closed before the next one is opened, even if the delay is added between connections
The following program is my experimental code. It does not throw exceptions and terminates normally in the current state However, if the array size of socket [] client increases to more than 50, any client socket trying to connect after the 50th connection will be rejected by the server socket
Question: why is the count of server sockets rejecting socket connections 50?
public static void main(String[] args) { try (ServerSocket server = new ServerSocket(2123)) { Socket[] clients = new Socket[50]; for (int i = 0; i < clients.length; i++) { clients[i] = new Socket("localhost",2123); System.out.printf("Client %2d: " + clients[i] + "%n",i); clients[i].close(); } } catch (Exception e) { e.printStackTrace(); } }
I have run the test. Another 50 sockets are connected to another local server, and there is no problem that 100 sockets are opened and closed, so I infer that its server socket refuses to connect, rather than some restrictions on opening the client socket, but I have been unable to find out why the server socket is limited to 50 connections, Even if they are not connected at the same time
Solution
All this is in Javadoc:
Obviously, your ServerSocket never accepts any connection, just listens You must call accept() and start processing the connection or increase the backlog queue size:
new ServerSocket(port,100)