2016-11-16 35 views
-1

这是在UDP服务器侧发送的字符串:
S:0 T:1 FL:4 IP:127.0.0.1,P:9000无法解析在客户端侧的整个UDP消息

我能够令牌化和打印,直到最后一个字,当我得到这个错误:

Exception in thread "Thread-2" java.lang.NumberFormatException: For input string: "9000 
at java.lang.NumberFormatException.forInputString(Unknown Source)  
at java.lang.Integer.parseInt(Unknown Source) 
at java.lang.Integer.parseInt(Unknown Source) 
at com.acn.fog.listener.UdpListener.tokenizeIotIntoPacket(UdpListener.java:119) 
at com.acn.fog.listener.UdpListener.run(UdpListener.java:43) 
at java.lang.Thread.run(Unknown Source) 

Server代码:

clientSocket = new DatagramSocket(); // make a Datagram socket 
    byte[] sendData = new byte[data.getBytes().length]; // make a Byte array of the data to be sent 
    sendData = data.getBytes(); // get the bytes of the message 
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); // craft the message to be sent 
    clientSocket.send(sendPacket); // send the message 

客户端代码:

byte[] receiveData = new byte[10000]; // data size not to exceed ~10KB 
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); // receive the response 
    serverSocket.receive(receivePacket); 
    // Tokenize received IOT packet into String 
    String iotPacketString = new String(receivePacket.getData()); 

感谢有关此问题的任何帮助。由于

+0

你确定你没有在某处调用'Integer.parseInt'吗? –

+0

看起来你可能只需要在调用'parseInt'之前先调整你的字符串,但是我不能告诉你没有提供正确的代码。 –

+0

@ScaryWombat非常感谢。我没有使用修剪。现在我使用trim和我的解析工作没有问题。 我很困惑,我不得不处理一些EOL字符,因为发件人代码没有附加任何空格。 – Vincy

回答

0

Unable to parse the entire UDP message at client side

您解析比整个UDP消息:

String iotPacketString = new String(receivePacket.getData()); 

无效。你忽略了长度。那应该是:

String iotPacketString = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); 
+0

谢谢。对我来说,这似乎比添加trim(),也有效。 – Vincy

+0

'trim()'不正确。任何消息都可以正确地包含前导空格或尾随空格,除了可以通过'trim()'去除的东西之外,还可以在字节数组的末尾留下其他数据:例如,先前的更长的消息的残余。 – EJP