我正在从 DatagramSocket 接收一条 UDP 消息,并尝试像这样解析该消息:
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);
我收到以下异常:
java.lang.NumberFormatException: For input string: "8080"
因此,调试输出给出的接收字符串有问题:
The String: /192.168.0.11 8080 has the length 256
有人知道为什么会发生这种情况吗?
最佳答案
提供了长度,但您忽略了它。应该是:
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());
关于java - 收到的 UDP 消息长度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533359/