简体   繁体   中英

java udp detect packet corruption

how can i detect udp packet corruption in java?

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:

        }
    }
}

}

packet corruption might happen. how do i have to handle packet corruption problem using udp? and i know how to detect packet loss but i don't know how to detect packet corruption.

If you absolutely need to use only DatagramPacket - Then, it doesn't expose any api to query the the transmitted checksum. What you can implement as a solution is have a logic(SHA256, MD..) to calculate the checksum, transmit the checksum as a payload in an alternating UDP packets, and compare the checksum calculated on the data payload vs checksum received on the next UDP segment. Ofcourse, you need to handle lot more error conditions in the suggested solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM