简体   繁体   English

java udp检测数据包损坏

[英]java udp detect packet corruption

how can i detect udp packet corruption in java? 如何在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:

        }
    }
}

} }

packet corruption might happen. 数据包损坏可能会发生。 how do i have to handle packet corruption problem using udp? 我如何使用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. 如果您绝对只需要使用DatagramPacket-那么,它不会公开任何api来查询传输的校验和。 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. 作为解决方案,您可以实现一个逻辑(SHA256,MD ..)来计算校验和,将校验和作为有效载荷发送到交替的UDP数据包中,并比较在数据有效载荷上计算出的校验和与下一个接收到的校验和之间的比较。 UDP段。 Ofcourse, you need to handle lot more error conditions in the suggested solution. 当然,在建议的解决方案中,您需要处理更多的错误情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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