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 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 theDatagramPacket
buffer without regard to how many bytes are actually in that buffer.DatagramPacket.getData()
does not return a newbyte[]
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 bysplit("\\s+")
, sosplitResp[1]
, and thusstrPort
, ends up with more than just digit characters in it, thus violating the requirements ofInteger.parseInt()
.You need to take the
DatagramPacket
length into account when constructingstrResp
:The length is provided, and you're ignoring it. It should be: