使用 NIO DatagramChannel 我需要处理部分读/写的数据包吗?

发布于 2024-07-16 09:15:36 字数 271 浏览 7 评论 0原文

使用SocketChannel时,需要保留读写缓冲区来处理部分写入和读取。

我一直怀疑使用 DatagramChannel 时可能不需要它,但信息很少。

这是什么故事?

我应该重复调用(非阻塞)receive(ByteBuffer) 直到我返回 null 来读取所有等待的数据报吗?

当以非阻塞模式发送时,我可以依靠 send(ByteBuffer, SocketAddress) 来发送整个缓冲区或完全拒绝它,或者我是否需要保留部分写入的缓冲区?

When using SocketChannel, you need to retain read and write buffers to handle partial writes and reads.

I have a nagging suspicion that it might not be needed when using a DatagramChannel, but info is scarce.

What is the story?

Should I call (non-blocking) receive(ByteBuffer) repeatedly until I get a null back to read all waiting datagrams?

When sending in non-blocking mode, can I rely on send(ByteBuffer, SocketAddress) to either send the the whole buffer or rejecting it entirely, or do I need to possibly keep partially written buffers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神经大条 2024-07-23 09:15:36

每次读取数据报都是整个数据报,不多也不少。 java.nio.DatagramChannel.read 的描述中暗示了这种情况:

如果有更多字节
数据报比保留在给定的
缓冲然后剩余的
数据报被默默丢弃

当你处理 SocketChannel 时,它是一个消息流; 无法保证每次读取时会获得多少数据,因为 TCP 正在重新组装单独的数据包以重新创建来自另一端的消息。 但对于 UDP(即您使用 DatagramChannel 读取的内容),每个数据包都是其自己的原子消息。

Every read of a Datagram is the entire datagram, nothing more, nothing less. There's a hint that this is the case in the description of java.nio.DatagramChannel.read:

If there are more bytes in the
datagram than remain in the given
buffers then the remainder of the
datagram is silently discarded

When you're dealing with a SocketChannel, it's a message stream; there's no guarantee how much or how little data you'll get on each read, as TCP is reassembling separate packets to recreate the message from the other side. But for UDP (which is what you're reading with the DatagramChannel) each packet is its own atomic message.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文