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

时间:2014-10-08 16:56:35

标签: java sockets byte datagram

所以我正在用Java编写一个程序,它在DatagramSocket和DatagramPacket的帮助下发送和接收数据。问题是介于我发送数据/接收数据之间的某个地方 - 数据在我发送的程序中变得不同,但仅在某些情况下这样:

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

但有时会工作,例如:

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

我正在发送两个坐标,首先将其转换为包含以下内容的字符串:

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

然后将字符串转换为字节数组,以便能够使用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();
}

这是我接收数据的线程:

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());
}

这是我“处理”收到的数据包的方法:

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

然后我将用两个坐标创建的点添加到我的程序中。我不知道在这个过程中哪里出错了。一些新观点会很酷!感谢。

1 个答案:

答案 0 :(得分:1)

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

这应该是

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