I am recieving a UDP message from a DatagramSocket and am trying to parse the message like this:
this.broadSock.receive(recvPacket);
// Decode response
byte[] response = recvPacket.getData();
String strResp = new String(response);
String[] splitResp = strResp.split("\\s+");
log.debug("The String: " + strResp + " has the length " + strResp.length());
InetAddress lobbyAdress = InetAddress.getByName(splitResp[0].substring(1));
String portStr = splitResp[1];
int lobbyPort = Integer.parseInt(portStr);
I am getting the following Exception:
java.lang.NumberFormatException: For input string: "8080"
So there is something wrong with the received String as the debug output gives me:
The String: /192.168.0.11 8080 has the length 256
Anybody an idea why this is happening?
The length is provided, and you're ignoring it. It should be:
String strResp = new String(packet.getData(), packet.getOffset(), packet.getLength());
String[] splitResp = strResp.split("\\s+");
log.debug("The response: " + strResp + " has the length " + packet.length());
The fact that strResp.length
is 256 is a symptom of a bug in your code. It should be 18 instead.
You are constructing strResp
using the entire length of the DatagramPacket
buffer without regard to how many bytes are actually in that buffer. DatagramPacket.getData()
does not return a new byte[]
for just the bytes received. It returns the entire buffer.
That means strResp
ends up with 238 extra characters after the port number, and they are not whitespace characters that would be stripped off by split("\\s+")
, so splitResp[1]
, and thus strPort
, ends up with more than just digit characters in it, thus violating the requirements of Integer.parseInt()
.
You need to take the DatagramPacket
length into account when constructing strResp
:
byte[] response = recvPacket.getData();
int responseOffset = recvPacket.getOffset();
int responseLength = recvPacket.getLength();
String strResp = new String(response, responseOffset, responseLength);