SocketChannel.write() 在单个线程中处理多个客户端
我的应用程序有一个队列,其中包含“传出网络数据包”(带有 ByteBuffer
和 SocketChannel
的 POJO),由将数据写入 的单个线程使用>SocketChannel
。
我这样做是为了保证每个应该接收数据包的客户端都能轮到。这意味着 SocketChannel.write() 会按顺序写入多个客户端(= 一次 1 个)。
谁能告诉我这样工作会出什么问题吗? SocketChannel
是从 ServerSocketChannel
创建的,因此它们是阻塞的。
我担心 write()
操作可能会阻塞 1 个客户端,使其他客户端等待......
my application has a queue with " outgoing network packets" (A POJO with a ByteBuffer
and a SocketChannel
) inside, consumed by a single thread that writes the data to the SocketChannel
.
I do this to guarantee that every client that should receive packets, gets its turn. This means that SocketChannel.write()
writes sequentially to multiple clients (= 1 at a time).
Can anyone tell me what could go wrong working like this? The SocketChannels
are created from a ServerSocketChannel
, so they're blocking.
I fear that the write()
operation could block for 1 client, making the other clients wait...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
write() 操作确实可以在阻塞模式下阻塞。如果你想要公平和单线程,你将不得不使用非阻塞模式。
The write() operation can indeed block in blocking mode. If you want fairness and single threading you will have to use non-blocking mode.
如果客户端套接字无法在一次写入(非阻塞)中消耗完所有数据,您可以关闭客户端。这仅在缓冲区填满时才会发生,因此您可以将套接字的发送缓冲区增加到您可以轻松执行此操作的水平。
If a client socket fails to consume all the data in one write (non-blocking), you could close the client. This will only happen when the buffer fills, so you could increase the send buffer of the socket to a level where you are comfortable doing this.