什么会导致 UDP 数据包在发送到本地主机时被丢弃?概述总结延伸阅读
我正在发送非常大的(64000字节)数据报。我意识到MTU比64000字节小得多(从我的阅读来看,典型值约为1500字节),但我怀疑会发生以下两种情况之一 - 要么没有数据报能够通过(大于1500字节的所有内容都会被静默丢弃或导致抛出错误/异常),要么64000字节的数据报将被分块为大约43 1500字节的消息并透明地传输。
从长远来看(2000+ 64000字节数据报),大约1%的数据报(即使是LAN似乎异常高)的数据报都会被丢弃。我可能期望通过网络来实现这一点,其中数据报可以无序到达,被丢弃,过滤等等。但是,在本地主机上运行时,我没想到会这样。
是什么原因导致无法在本地发送/接收数据?我意识到UDP是不可靠的,但我没想到它在localhost上如此不可靠。我想知道这是否只是一个时间问题,因为发送和接收组件都在同一台计算机上。
为了完整起见,我包含了用于发送/接收数据报的代码。
发送:
DatagramSocket socket = new DatagramSocket(senderPort);
int valueToSend = 0;
while (valueToSend < valuesToSend || valuesToSend == -1) {
byte[] intBytes = intToBytes(valueToSend);
byte[] buffer = new byte[bufferSize - 4];
//this makes sure that the data is put into an array of the size we want to send
byte[] bytesToSend = concatAll(intBytes, buffer);
System.out.println("Sending " + valueToSend + " as " + bytesToSend.length + " bytes");
DatagramPacket packet = new DatagramPacket(bytesToSend,
bufferSize, receiverAddress, receiverPort);
socket.send(packet);
Thread.sleep(delay);
valueToSend++;
}
接收:
DatagramSocket socket = new DatagramSocket(receiverPort);
while (true) {
DatagramPacket packet = new DatagramPacket(
new byte[bufferSize], bufferSize);
System.out.println("Waiting for datagram...");
socket.receive(packet);
int receivedValue = bytesToInt(packet.getData(), 0);
System.out.println("Received: " + receivedValue
+ ". Expected: " + expectedValue);
if (receivedValue == expectedValue) {
receivedDatagrams++;
totalDatagrams++;
}
else {
droppedDatagrams++;
totalDatagrams++;
}
expectedValue = receivedValue + 1;
System.out.println("Expected Datagrams: " + totalDatagrams);
System.out.println("Received Datagrams: " + receivedDatagrams);
System.out.println("Dropped Datagrams: " + droppedDatagrams);
System.out.println("Received: "
+ ((double) receivedDatagrams / totalDatagrams));
System.out.println("Dropped: "
+ ((double) droppedDatagrams / totalDatagrams));
System.out.println();
}