简体   繁体   English

收到的UDP消息长度不正确

[英]Received UDP message has incorrect length

I am recieving a UDP message from a DatagramSocket and am trying to parse the message like this: 我正在从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);

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: 因此,接收到的String出了问题,因为调试输出给了我:

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. strResp.length为256的事实表明代码中存在错误。 It should be 18 instead. 应该是18。

You are constructing strResp using the entire length of the DatagramPacket buffer without regard to how many bytes are actually in that buffer. 您正在使用DatagramPacket缓冲区的整个长度构造strResp ,而不考虑该缓冲区中实际上有多少字节。 DatagramPacket.getData() does not return a new byte[] for just the bytes received. DatagramPacket.getData()不会仅为接收到的字节返回新的byte[] 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() . 这意味着strResp在端口号之后以238个额外的字符结尾,并且它们不是将由split("\\\\s+")剥离的空格字符,因此splitResp[1]strPort最终以大于只是其中的数字字符,从而违反了Integer.parseInt()的要求。

You need to take the DatagramPacket length into account when constructing strResp : 构造strResp时,需要考虑DatagramPacket长度:

byte[] response = recvPacket.getData();
int responseOffset = recvPacket.getOffset();
int responseLength = recvPacket.getLength();
String strResp = new String(response, responseOffset, responseLength);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM