Java中的OutputStream是阻塞的吗? (插座) [英] Is an OutputStream in Java blocking? (Sockets)

查看:179
本文介绍了Java中的OutputStream是阻塞的吗? (插座)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为一个项目编写天真的网络代码,并且一位伙伴暗示我有可能当我以一种迭代的方式从服务器向所有客户端发送信息包时,当其中一个客户端是没有正确回复。

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 iterative fashion I might get intense lag when one of the clients is not responding properly.

他因拖钓而闻名,所以当我实现一个现在负责将数据发送到客户端,有队列的辅助线程时,我有点怀疑服务器只是简单地添加包然后由线程读取以发送数据。

He is reknown for trolling so I was kind of sceptical when implementing a secondary thread that is now responsible to send data over to a client, having a queue that the Server simply adds the packages over that is then read by the thread to send data.

我认为现在的问题是天气或不是OutputStream Java Socket实际上将他想要发送的东西排队,因此事先不需要队列。只有当客户端没有收到来自收到发送对象的客户的响应时,才会出现发生严重问题的可能性。

The question I now have after thinking it over is weather or not the OutputStream of a Java Socket actually queues the stuff he wants to send by itself, thus eliminating the need of a queue beforehand. The possibility of having intense problems occurrs only when the Server is blocking as long as he does not get a response from a client that the sent object was recieved.

谢谢。

推荐答案

当然,当你写一个套接字时,这个写是缓冲的。 Socket对象有一个 setSendBufferSize()方法来设置此缓冲区大小。如果您的写入可以缓存在此缓冲区中,那么您当然可以立即在以下套接字上进行迭代。否则,需要立即将此缓冲区刷新到客户端。因此,在冲洗期间,您将被阻止。如果要在刷新缓冲区时避免被阻塞,则必须在非阻塞I / O中使用 SocketChannel
无论如何,同时写入多个套接字的最佳选择是使用不同的线程管理每个套接字,以便所有写入可以同时执行。

Of course, when you write to a socket, this write is buffered. Socket object have a setSendBufferSize() method for setting this buffer size. If your write can be cached in this buffer, then of course, you may iterate immediately on the following socket. Otherwise this buffer need to be flushed to the client immediately. So, during flushing you are going to be blocked. If you want to avoid being blocked while flushing the buffer, you have to use a SocketChannel in non blocking I/O. Anyway, the best option for writing to many socket concurrently, is to manage each socket with a different thread, so that all writes may be executed at the same time.

这篇关于Java中的OutputStream是阻塞的吗? (插座)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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