发送数据时Java的TCP套接字类是否阻塞 [英] Does Java's TCP Socket class block when sending data

查看:183
本文介绍了发送数据时Java的TCP套接字类是否阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

推荐答案

TCP握手发生在connect(2)时间,而不是发生在write(2)时间.

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

write(2)的调用将一直阻塞,直到OS TCP发送缓冲区已耗尽,足以从程序接受更多数据为止. (我无法想象操作系统会为单个空闲字节解除对write(2)操作的阻塞.)

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.)

您拥有的唯一保证是,客户端过去已接受数据,并且不会比会话的TCP窗口大小加上内部OS缓冲区的大小落后.这些数据是否到达另一端点的 application 还是缓冲区的另一层-远程对等方上的TCP堆栈将确认收到的数据并将其存储在应用程序之前有机会进行处理.

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.

这篇关于发送数据时Java的TCP套接字类是否阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆