套接字编程:java.lang.NumberFormatException:对于输入字符串:“1”

时间:2016-12-03 12:58:04

标签: java sockets udp

我通过UDP套接字和数据包发送消息:mesajes具有以下格式:

"MESSAGE" + SEPARATOR + "IDCLIENT"

以下是客户端上的代码:

String msg = "MESSAGE" + SEPARATOR + id;
byte[] msgBytes = msg.getBytes();
DatagramPacket p = new DatagramPacket(msgBytes, msgBytes.length, serverIP, SERVER_PORT);

DatagramSocket socket = new DatagramSocket();
socket.send(p);

以下是服务器上的代码:

DatagramSocket socket = new DatagramSocket ( SERVER_PORT );
byte[] buffer = new byte[BUFFER_MSG];
DatagramPacket p = new DatagramPacket (buffer, buffer.length);
socket.receive(p);

// Here comes where my problem appears
String msg = new String ( p.getData() );
msg.trim(); //this is suposed to solve my problem, but it doesn't
String[] msgParts = msg.split(SEPARATOR);

if (msgParts.length == 2)
{
    String infoMsg = msgParts[0];
    int id = Integer.parseInt( msgParts[1] ); // Here the get the NumberFormatException
}

// Do more...

我不理解错误消息:java.lang.NumberFormatException: For input string: "1"。因为据我所知,字符串"1"应该转换为整数1

PS:为了清楚起见,我遗漏了IOException的try-catch标记。

1 个答案:

答案 0 :(得分:0)

msg.trim();更改为msg = msg.trim();                      - Elliott Frisch