简体   繁体   English

与数据报一起发送后从String解析int时发生异常

[英]Exception when parsing int from String after it was sent with Datagram

I'm starting to feel real stupid - and hopefully this question's got a simple answer. 我开始感到真正的愚蠢-希望这个问题能得到一个简单的答案。

I'm trying to send the coordinates of a Point object over UDP. 我正在尝试通过UDP发送Point对象的坐标。 The sending works great: 发送效果很好:

public void send(Point p) throws IOException {
        String data = Integer.toString(p.x) + " " + Integer.toString(p.y);
        InetAddress IPAddress = InetAddress.getByName(this.remoteHost);
        byte[] sendData = new byte[1024];
        sendData = data.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, this.remotePort);
        socket.send(sendPacket);
}

And I can receive the data on the other end: 我可以在另一端接收数据:

byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
this.socket.receive(receivePacket);

As you might see I'm sending the String "XY", for example "329 456". 您可能会看到,我正在发送字符串“ XY”,例如“ 329 456”。 I now need to parse those values to integers, so I can use them on the other end: 现在,我需要将这些值解析为整数,以便可以在另一端使用它们:

String[] parts = data.split(" ");
int x = Integer.parseInt(new String(parts[0]));
int y = Integer.parseInt(new String(parts[1]));

But this gives me a NumberFormatException on the y integer ("For input string: '456'"). 但这给了我一个关于y整数的NumberFormatException(“对于输入字符串:'456'”)。 Why? 为什么? Is there anything I'm missing here? 我在这里想念什么吗? I've been thinking about he actual encoding of the characters send - could that be the reason why Integer won't understand the value? 我一直在考虑他发送的字符的实际编码-这可能是Integer无法理解值的原因吗?

Thank you for any help. 感谢您的任何帮助。

I guess you don't take packet length into account when converting packet data to String . 我猜您在将数据包数据转换为String时没有考虑数据包长度。

You should do it as follows: 您应该按照以下步骤进行操作:

String data = new String(receivePacket.getData(), 0, receivePacket.getLength());

Also, it would be better to specify character encoding explicitly when sending and receiving the message, to prevent issues when machines have different default encodings: 另外,最好在发送和接收消息时明确指定字符编码,以防止机器使用不同的默认编码时出现问题:

sendData = data.getBytes("UTF-8");
...
String data = new String(receivePacket.getData(), 0, receivePacket.getLength(), "UTF-8");

您是否以这种方式读取数据?

String data = new String(receivePacket.getData(), 0, receivePacket.getLength());

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

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