Vincy Vincy - 9 months ago 46
Java Question

Unable to parse the entire UDP message at client side

This is the String sent at UDP server side:

S:0 T:1 FL:4 IP: P:9000

I am able to tokenize and print up until the last word, when I get this error:

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(
at Source)

Server code:

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

Client code:

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

Appreciate any help on this issue. Thanks

Answer Source

Unable to parse the entire UDP message at client side

You are parsing more than the entire UDP message:

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

Invalid. You're ignoring the length. That should be:

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