简体   繁体   English

Datagramsocket:接收(...)如何处理数据包的碎片

[英]Datagramsocket: how receive(…) handles fragmentation of a packet

I came to know from my Professor that, a datagram packet sent using UDP socket gets fragmented in the lower layers and may arrive as multiple packets at the receiver end. 我从我的教授那里得知,使用UDP套接字发送的数据报包在较低层中被分段,并且可能在接收器端以多个数据包的形式到达。 For eg, if I send a 1000 bytes data in a datagram packet, at the receiving end it might arrive as, say 2 bytes, 500 bytes, 12 bytes, and so on. 例如,如果我在数据报包中发送1000字节数据,则在接收端它可能会以2字节,500字节,12字节等形式到达。 Therefore, he suggested to do multiple receive(...) to receive the entire 1000 byte packet sent by the sender. 因此,他建议多次接收(...)接收发送方发送的整个1000字节的数据包。

Later when I went through the Java documentation for datagram socket receive(...) and there is a line that reads as follows: "This method blocks until a datagram is received. ..." Does it mean that entire datagram packet is received and don't need to do multiple receive (even though it's the case in theory) when we use Java? 后来当我浏览数据报套接字接收(...)的Java文档时,有一行读取如下:“此方法阻塞,直到收到数据报。...”是否表示收到整个数据报包当我们使用Java时,不需要进行多次接收(即使理论上是这种情况)?

Pls. PLS。 clarify. 澄清。 If multiple receive(...) for each packet is the only option to get around this problem, pls. 如果每个数据包的多次接收(...)是解决此问题的唯一选择,请参阅。 give suggestions on how to do this. 提出如何做到这一点的建议。

Any call to receive() will give you an entire packet - the fragment handling happens in two layers below the socket. receive()任何调用都会给你一个完整的数据包 - 片段处理发生在套接字下面的两层。 The fragmentation and defragmentation happens in the Network/Internet layer ( IP ), so the socket will never see the fragments but only receive entire and full UDP/TCP packets (only full packets gets sent to the listening port). 碎片和碎片整理发生在网络/ Internet层( IP )中,因此套接字永远不会看到碎片但只接收完整和完整的UDP / TCP数据包(只有完整的数据包才会被发送到监听端口)。

So, no, you do not need multiple receive() to get a single packet, but you should be aware that UDP is not reliable so if one fragment gets lost in the Network layer (and in some cases if it arrives out of order), you won't be able to get the packet. 所以,不,你不需要多个receive()来获取单个数据包,但是你应该知道UDP不可靠,所以如果一个片段在网络层中丢失(在某些情况下,如果它不按顺序到达) ,你将无法获得数据包。

You might also want to check the methods getReceiveBufferSize() and setReceiveBufferSize() if you're having trouble receiving packets - if the buffer size is smaller than the packet size, it's not guaranteed that you can receive the packet. 如果您在接收数据包时遇到问题,您可能还需要检查方法getReceiveBufferSize()setReceiveBufferSize() - 如果缓冲区大小小于数据包大小,则无法保证您可以接收数据包。

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

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