我使用 UDP 连接向计算机 2 发送 3 条消息时遇到问题,它只能在计算机 2 中获取最后一条消息
String service = "deposit"; //send service
byteSend = service.getBytes();
sendPacket.setData(byteSend);
sendPacket.setAddress(destAdd);
sendPacket.setPort(destPort);
otherBranch.send(sendPacket);
byteSend1 = accNo.getBytes(); //send accNo
sendPacket.setData(byteSend1);
sendPacket.setAddress(destAdd);
sendPacket.setPort(destPort);
otherBranch.send(sendPacket);
byteSend2 = depositAmount.getBytes(); //send depositAmount
sendPacket.setData(byteSend2);
sendPacket.setAddress(destAdd);
sendPacket.setPort(destPort);
otherBranch.send(sendPacket);
之后,computer2 有此代码可以接收:
myServer.receive(packetReceive);
clientMessage = new String(packetReceive.getData(),0,packetReceive.getLength());
System.out.println("Service: "+clientMessage);
myServer.receive(packetReceive);
accNo = new String(packetReceive.getData(),0,packetReceive.getLength());
System.out.println("accNo: "+accNo);
myServer.receive(packetReceive);
depositAmount = new String(packetReceive.getData(),0,packetReceive.getLength());
System.out.println("depositAmount: "+depositAmount);
为什么输出只能得到我的最后一个值,即depositAmount?
最佳答案
您的代码没有传输节奏。使用 TCP,堆栈会为您传输节奏。对于 UDP,这是您的责任。
您需要编写代码来检测丢失的数据报并重新传输它们。 UDP 不保证消息传送。这就是应用程序的工作。
如果您需要 TCP 所做的一切,但您选择使用 UDP,则必须自己实现所有这些。
这包括:
传输节奏。
指数退避。
丢弃数据报检测和重传。
重复数据报检测。
无序接收处理。
损坏的数据报检测。
如果您不想做所有这些事情,请使用 TCP。然后堆栈会为您完成这一切。
关于java - UDP消息无法在computer2中成功获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13803204/