线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“100”

时间:2017-11-21 21:44:18

标签: java sockets udp

当接收到从单独的客户端程序转换为字符串的整数(事务ID)时,我的Java UDP服务器程序片段出现错误:

客户端:

// Sending transaction ID to server
sendData = String.valueOf(transID).getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, sportno);
clientSocket.send(sendPacket);

SERVER:

// Receive client's transaction ID
receiveData = new byte[1024]; // 1024 byte limit when receiving
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket); // Server receives packet "100" from client
String clientMsg = new String(receivePacket.getData()); // String to hold received packet
int transID = Integer.valueOf(clientMsg); // Convert clientMsg to integer
System.out.println("Client has sent: " + transID); // Printing integer before iteration

虽然客户端发送数据包很好,但在字符串到整数转换期间我收到此错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "100"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at server.main(server.java:46)

我也使用了类似结果的Integer.parseInt(clientMsg)。但是,只要我没有尝试将数据包转换为整数,该程序就可以将数据包打印为字符串值。

此外,虽然它在终端中显示了这一点,但当我将此错误消息复制+粘贴到此帖子中时,“100”后面跟着大量的“s”,我假设剩下的是空的来自receiveData变量的字节。

这些空值是我的程序失败的原因吗?如果没有,该程序还有什么其他原因失败?另外,有没有办法将事务ID整数发送到服务器而不首先将其转换为字符串以防止此错误?

2 个答案:

答案 0 :(得分:0)

尝试希望这是有效的

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

答案 1 :(得分:0)

String clientMsg = new String(receivePacket.getData()); // String to hold received packet

问题出在这里。您通过忽略传入数据报的实际长度来追加垃圾。它应该是:

String clientMsg = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String to hold received packet