Does Java's TCP Socket class block when sending data

China☆狼群 提交于 2020-05-29 11:37:21

问题


When I use Javaa's Socket class to send out a byte array, does the write call in the following code block until it has verified that the recipient has received the data?

byte data[] = ...;
Socket socket = ...;

socket.getOutputStream().write(data); // blocking ?

The reason I ask, is if I have a list of sockets that I want to send the same data to, I want to send it as efficiently as possible, i.e., is there a better way than this:

ArrayList<Socket> sockets = ...;
byte data[] = ...;

for(int i = 0; i < sockets.size(); i++)
  sockets.getOutputStream().write(data);

回答1:


The TCP handshake happens at connect(2) time, not at write(2) time.

Calls to write(2) will block until the OS TCP send buffer is depleted enough to accept more data from the program. (I can't imagine the OS unblocking the write(2) operation for a single free byte.)

The only guarantee you have is that the client has accepted data in the past, and is not further behind than the size of the TCP window for the session plus the size of the internal OS buffers. Whether or not any of that data has reached the application on the other end point is yet another layer of buffers -- the TCP stack on the remote peer will acknowledge received data and store it in buffers before the application has an opportunity to process it.



来源:https://stackoverflow.com/questions/5137212/does-javas-tcp-socket-class-block-when-sending-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!