简体   繁体   中英

Receiving/sending datagram socket data

so I'm doing a program in Java that sends and receives data with the help of DatagramSocket and DatagramPacket. The problem is that somewhere between when i'm sending the data/receiving it - the data turns up to be different in the program i'm sending it too, but only in certain cases like this:

Sending: 378 Receiving: 3786
Sending: 374 Receiving: 3742
Sending: 360 Receiving: 3604

But works sometimes, in cases like:

Sending: 376 Receiving: 376
Sending: 372 Receiving: 372
Sending: 344 Receiving: 344

I'm sending two coordinates, to first convert it to a string with:

String message = Integer.toString(coord1) + " " + Integer.toString(coord2);

Then converting the string to a byte array to be able to send it with a DatagramPacket:

byte[] b = message.getBytes(Charset.forName("UTF-8"));
DatagramPacket packet = new DatagramPacket(b, b.length, remoteHost, remotePort);

try {
    datagramSocket.send(packet);
} catch(Exception e) {
    e.printStackTrace();
}

This is my thread that receives the data:

private DatagramSocket dSocket;
private DatagramPacket packet;
private byte[] buffer;
private PaintProgram prog;

public ReceiverThread(int myPort, PaintProgram prog) {
    this.prog = prog;

    try {
        buffer = new byte[256];
        dSocket = new DatagramSocket(myPort);
        packet = new DatagramPacket(buffer, buffer.length);
    } catch(Exception e) {
        e.printStackTrace();
    }

    this.start();
}

@Override
public void run(){
    do{
        try {
            dSocket.receive(packet);
            String data = new String(buffer, "UTF-8");
            prog.handlePacket(data);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
    while(!this.currentThread().isInterrupted());
}

And this is my method that "handles" the packet that's received:

String[] xy = data.split(" ");
Point point = new Point(Integer.parseInt(xy[0].trim()), Integer.parseInt(xy[1].trim()));

Then i add the point created with the two coordinates to my program. I don't know where in this process it goes wrong. Would be cool with some new perspective! Thanks.

String data = new String(buffer, "UTF-8");

这应该是

String data = new String(packet.getData(), packet.getOffset(), packet.getLength(), "UTF-8");

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