【问题标题】:Exception in thread "main" java.lang.NumberFormatException: For input string: "100" [duplicate]线程“main”java.lang.NumberFormatException中的异常:对于输入字符串:“100”[重复]
【发布时间】: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整数发送到服务器而不先将其转换为字符串以防止出现此错误?

【问题讨论】:

标签: java sockets udp


【解决方案1】:
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

【讨论】:

  • 成功了,感谢您的帮助。我有一个关于其他方法如何工作的问题:上述方法是否通过首先使用 .getLength() 获取非空值的长度来删除额外的垃圾,然后使用 .getOffset() 删除所有“空”垃圾超出这个长度?
【解决方案2】:

试试希望这行得通

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

【讨论】:

  • Datagram 不存在,DatagramPacket.getData() 返回一个字节数组,在字节数组上调用toString() 不会产生内容。
  • 现在你只是抄袭,没有任何解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2014-06-07
相关资源
最近更新 更多