2014-10-16 83 views
1

如何檢測java中的udp數據包損壞?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

如果您絕對只需要使用DatagramPacket - 那麼它不會公開任何API來查詢傳輸的校驗和。作爲一種解決方案,您可以實現一個邏輯(SHA256,MD ..)來計算校驗和,在交替的UDP數據包中將校驗和作爲有效載荷進行傳輸,並比較數據有效載荷上計算的校驗和與下一次接收的校驗和UDP段。當然,您需要在建議的解決方案中處理更多的錯誤條件。