简体   繁体   English

Java:为什么DatagramSocket的`receive`方法会截断消息?

[英]Java: why does DatagramSocket's `receive` method truncate messages?

Coming from a C socket() / recv() background, the Java DatagramSocket.receive API seems a bit strange. 来自C socket() / recv()背景,Java DatagramSocket.receive API似乎有点奇怪。 Why does force the programmer to allocate a DatagramPacket large enough for the incoming data? 为什么强制程序员为传入数据分配足够大的DatagramPacket

This question is based on a false premise. 这个问题是基于一个错误的前提。 In C, the signature for the recv syscall is: 在C中, recv系统调用的签名是:

ssize_t recv(int s, void *buf, size_t len, int flags);

Note that you pass a pointer to a buffer, and the length of that buffer. 请注意,您将指针传递给缓冲区,以及该缓冲区的长度。 The manual entry then says: 然后手动输入说:

If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from. 如果消息太长而无法容纳在提供的缓冲区中,则可能会丢弃多余的字节,具体取决于接收消息的套接字类型。

In other words, the C API expects the caller to allocate a "large enough" buffer, and may truncate messages that are longer ... just like Java does. 换句话说,C API期望调用者分配一个“足够大”的缓冲区,并且可能截断更长的消息......就像Java那样。

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

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