无法在客户端解析整个UDP消息

时间:2016-11-16 01:39:11

标签: java string sockets udp tokenize

这是在UDP服务器端发送的字符串:
S:0 T:1 FL:4 IP:127.0.0.1 P:9000

我能够标记并打印到最后一个字,当我收到此错误时:

Exception in thread "Thread-2" java.lang.NumberFormatException: For input string: "9000  
at java.lang.NumberFormatException.forInputString(Unknown Source)    
at java.lang.Integer.parseInt(Unknown Source)  
at java.lang.Integer.parseInt(Unknown Source)  
at com.acn.fog.listener.UdpListener.tokenizeIotIntoPacket(UdpListener.java:119)  
at com.acn.fog.listener.UdpListener.run(UdpListener.java:43)  
at java.lang.Thread.run(Unknown Source)  

服务器代码:

    clientSocket = new DatagramSocket(); // make a Datagram socket  
    byte[] sendData = new byte[data.getBytes().length]; // make a Byte array of the data to be sent  
    sendData = data.getBytes(); // get the bytes of the message  
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); // craft the message to be sent  
    clientSocket.send(sendPacket); // send the message  

客户代码:

    byte[] receiveData = new byte[10000]; // data size not to exceed ~10KB  
    DatagramPacket receivePacket = new DatagramPacket(receiveData,   receiveData.length); // receive the response  
    serverSocket.receive(receivePacket);  
    // Tokenize received IOT packet into String  
    String iotPacketString = new String(receivePacket.getData());  

感谢您对此问题的任何帮助。谢谢

1 个答案:

答案 0 :(得分:0)

  

无法解析客户端的整个UDP消息

您正在解析 more 而不是整个UDP消息:

String iotPacketString = new String(receivePacket.getData()); 

无效。你忽略了长度。那应该是:

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