java 设置 sendBufferSize() 后 UDP 套接字的消息太长

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3396813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:38:48  来源:igfitidea点击:

Message too long for UDP socket after setting sendBufferSize()

java

提问by mo-seph

I'm trying to send a UDP datagram (containing a protocol buffers message) and getting message too long exceptions:

我正在尝试发送 UDP 数据报(包含协议缓冲区消息)并收到消息太长异常:

java.io.IOException: Message too long
at java.net.PlainDatagramSocketImpl.send(Native Method)
at java.net.DatagramSocket.send(DatagramSocket.java:625)

I've set the send buffer size, and checked the return value from getBufferSize(), and it's larger than the message:

我已经设置了发送缓冲区大小,并检查了 getBufferSize() 的返回值,它比消息大:

byte[] b = msg.toByteArray();
            System.out.println( "Serialised message in " + b.length + " bytes (max length: " + network.getSendBufferSize() + ")");
            DatagramPacket p = new DatagramPacket( b, b.length, host, port );
            network.send( p );

Outputs:

输出:

VM version: 16.3-b01-279
Runtime version: 1.6.0_20-b02-279-9M3165
Vendor: Apple Inc.    
Serialised message in 69424 bytes (max length: 531075)
Problem sending packet: java.io.IOException: Message too long

I could understand if it was refusing to set a large sized buffer, but it seems to be setting whatever I ask, and then not honoring it.

我可以理解它是否拒绝设置大缓冲区,但它似乎设置了我要求的任何内容,然后不尊重它。

This is on OSX; I've tried both with 1.6 and 1.5

这是在 OSX 上;我已经尝试过 1.6 和 1.5

采纳答案by Victor Sorokin

UDP datagrams can't be larger than 64K

UDP 数据报不能大于 64K

回答by user207421

  1. The limit on a UDP datagram payload in IPv4 is 65535-28=65507 bytes, and the practical limit is the MTU of the path which is more like 1460 bytes if you're lucky.

  2. When UDP is fragmented, it losesthe datagram if a fragment is lost, because there is noretransmission.

  1. IPv4 中 UDP 数据报负载的限制是 65535-28=65507 字节,实际限制是路径的 MTU,如果幸运的话,它更像是 1460 字节。

  2. 当 UDP 被分片时,如果一个分片丢失,它就会丢失数据报,因为没有重传。

Use TCP.

使用 TCP。

回答by ZZ Coder

UDP has a maximum limit a little bit short of 64K. Your message is over that limit.

UDP 的最大限制略低于 64K。您的消息超出了该限制。

Besides, you shouldn't use UDP at all for such large message. When UDP is fragmented, it has to retransmit the whole thing if one segment is lost. Use TCP.

此外,对于如此大的消息,您根本不应该使用 UDP。当 UDP 被分段时,如果丢失了一个段,它必须重新传输整个内容。使用 TCP。