2014-09-04 11 views
0

我开始感到真正的愚蠢 - 希望这个问题有一个简单的答案。使用数据报发送字符串后解析int时的异常

我想通过UDP发送一个Point对象的坐标。发送的伟大工程:

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

而且我可以接收另一端的数据:

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

正如你可能会看到我送的字符串“XY”,例如“329 456” 。我现在需要将这些值解析为整数,这样我就可以在另一端使用它们:

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

但是,这给了我一个NumberFormatException异常在y的整数(“对于输入字符串:‘456’”)。为什么?有什么我在这里失踪?我一直在考虑他发送字符的实际编码 - 这可能是整数不理解值的原因吗?

谢谢你的帮助。

+0

你试过调试吗?在尝试解析为int之前,“parts [0]”和“parts [1]”的值是什么?可能会有一些额外的字符 – Adi 2014-09-04 12:54:30

+0

打印零件[1]并确保它是一个int – 2014-09-04 12:55:02

回答

0

我想你在将数据包数据转换为String时不考虑数据包长度。

你应该这样做如下:

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

此外,发送和接收消息时,防止问题时,机器有不同的默认编码,这将是最好明确指定字符编码:

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

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

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