简体   繁体   English

发送数据时Java的TCP套接字类是否阻塞

[英]Does Java's TCP Socket class block when sending data

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? 当我使用Javaa的Socket类发送字节数组时,是否在下面的代码块中进行写调用,直到它确认接收者已接收到数据为止?

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, ie, is there a better way than this: 我问的原因是,如果我有要向其发送相同数据的套接字列表,我想尽可能高效地发送它,即,有没有比这更好的方法:

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

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

The TCP handshake happens at connect(2) time, not at write(2) time. TCP握手在connect(2)时间发生,而不是在write(2)时间发生。

Calls to write(2) will block until the OS TCP send buffer is depleted enough to accept more data from the program. write(2)调用将一直阻塞,直到OS TCP发送缓冲区已耗尽,足以从程序接受更多数据为止。 (I can't imagine the OS unblocking the write(2) operation for a single free byte.) (我无法想象操作系统会为单个空闲字节解锁write(2)操作。)

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. 您所拥有的唯一保证是,客户端过去已接受数据,并且不会比会话的TCP窗口的大小加上内部OS缓冲区的大小落后。 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. 是否有任何的数据已经达到在另一端点的应用是又缓冲器的另一层-远端对等节点将确认接收到的数据并将其存储在缓冲器中的应用程序有机会来处理它之前的TCP栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM