简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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