问题
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