2016-11-16 84 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