Is an OutputStream in Java blocking? (Sockets)

后端 未结 3 974
清歌不尽
清歌不尽 2021-02-19 03:35

I am currently writing naive network code for a project and a mate hinted me at the possibility that when I send a package of information from the server to all clients in an it

3条回答
  •  [愿得一人]
    2021-02-19 04:02

    Your friend is right but it has more to do with how tcpip protocol works. Largely simplifying packets sent to the client need to be confirmed. If the client is not responding (fails to read incoming data, computer is under heavy load, etc.) the server won't receive acknowledgements and will stop sending the data. This mechanism built into TCP/IP prevents one end of the communication from sending large amounts of data without making sure the other end received them. In turns this avoid the requirement to resend big amounts of data.

    In Java this manifests as blocking write to OutputStream. The underlying TCP/IP stack/operating system does not allow sending more data until the client is ready to receive it.

    You can easily test this! I implemented simple server that accepts connection but fails to read incoming data:

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                final ServerSocket serverSocket = new ServerSocket(4444);
                final Socket clientSocket = serverSocket.accept();
                final InputStream inputStream = clientSocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }).start();
    

    And a simple client that just sends as much data as it can in 4K batches:

    final Socket client = new Socket("localhost", 4444);
    final OutputStream outputStream = client.getOutputStream();
    int packet = 0;
    while(true) {
        System.out.println(++packet);
        outputStream.write(new byte[1024 * 4]);
    }
    

    The client loop hangs on my computer after 95 iterations (your mileage may vary). However if I read from inputStream in server thread - the loop goes on and on.

提交回复
热议问题