【发布时间】:2017-11-21 21:44:18
【问题描述】:
当我收到一个从单独的客户端程序转换为字符串的整数(事务 ID)时,我的 Java UDP 服务器程序的 sn-p 出现错误:
客户:
// Sending transaction ID to server
sendData = String.valueOf(transID).getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, sportno);
clientSocket.send(sendPacket);
服务器:
// 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”后面跟着大量“”,我假设其余的都是空的来自 receiveData 变量的字节。
这些空值会是我的程序失败的原因吗?如果不是,程序失败的其他原因是什么?另外,有没有办法将事务ID整数发送到服务器而不先将其转换为字符串以防止出现此错误?
【问题讨论】:
-
“这些空值会是我的程序失败的原因吗?”是的。