简体   繁体   English

接收/发送数据报套接字数据

[英]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.所以我正在用 Java 编写一个程序,该程序在 DatagramSocket 和 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:然后将字符串转换为字节数组,以便能够使用 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");

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

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