如何在java中检测udp数据包损坏?
public class PacketReceiver implements Runnable{
byte[] dataReceive = new byte[udpConnectionManager.MAX_PACKET_SIZE];
private ArrayList<Thread> workerList = new ArrayList<Thread>();
@Override
public void run() {
while(true){
DatagramPacket receivePacket = new DatagramPacket(dataReceive, dataReceive.length);
try {
udpConnectionManager.socket.receive(receivePacket);
} catch (IOException e) {
e.printStackTrace();
}
byte[] receivedData = receivePacket.getData();
//[0] stores basic command
//[1~4] int stores protocol id
//[5~9] int data increase counter for detect packet loss
//[10~14]
switch(receivedData[0]){
//initial packet
case 0x01:
if(!udpConnectionManager.instance.isInitialized(receivePacket)){
Thread t = new Thread(new AcceptThread(receivePacket));
t.start();
workerList.add(t);
}else{
System.out.println("initialized packet attempt to initialize.");
}
//heartbeat signal
case 0x02:
if(udpConnectionManager.instance.isInitialized(receivePacket)){
udpConnectionManager.instance.getConnection(receivePacket).onHeartBeat();
}else{
System.out.println("Received HeartBeat signal from non-initialized connection");
}
//
case 0x03:
}
}
}
}
可能会发生数据包损坏。我如何使用udp处理数据包损坏问题? 我知道如何检测数据包丢失,但我不知道如何检测数据包损坏。
答案 0 :(得分:0)
如果您绝对只需要使用DatagramPacket - 那么,它不会公开任何api来查询传输的校验和。您可以实现的解决方案是使用逻辑(SHA256,MD ..)来计算校验和,将校验和作为有效负载在交替的UDP数据包中传输,并比较在数据有效负载上计算的校验和与在下一个接收到的校验和之间的校验和UDP段。当然,您需要在建议的解决方案中处理更多错误条件。