开发者

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

开发者 https://www.devze.com 2023-02-09 11:57 出处:网络
Coming from a开发者_开发知识库 C socket()/recv() background, the Java DatagramSocket.receive API seems a bit strange. Why does force the programmer to allocate a DatagramPacket large enough for the in

Coming from a开发者_开发知识库 C socket()/recv() background, the Java DatagramSocket.receive API seems a bit strange. Why does force the programmer to allocate a DatagramPacket large enough for the incoming data?


This question is based on a false premise. In C, the signature for the recv syscall is:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消