Java ServerSocket connection limit?

后端 未结 4 2004
北恋
北恋 2020-12-10 04:57

I was running a few tests with sockets, and I encountered some strange behavior: A ServerSocket will refuse connections after the 50th client Socket connects to it, even if

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 05:31

    Here's an example that works, in accordance with @TomaszNurkiewicz's answer:

    import java.net.*;
    import java.util.concurrent.atomic.AtomicBoolean;
    
    public class SockTest{
    public static void main(String[] args) {
        final AtomicBoolean shouldRun = new AtomicBoolean(true);
        try  {
            final ServerSocket server = new ServerSocket(2123);
            Thread serverThread = new Thread(){
               public void run() {
                  try {
                     while(shouldRun.get()) {
                     Socket s = server.accept();
                     s.close();
                 Thread.sleep(1);
                    }
                  } catch(Exception ex) {
                    ex.printStackTrace();
                  }
               }
            };
            serverThread.start();
            Socket[] clients = new Socket[150];
            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();
            }
            shouldRun.set(false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           shouldRun.set(false);
        }
    
      }
    }
    

提交回复
热议问题