Java datagramsocket接收不完整的消息

时间:2016-04-07 18:54:03

标签: java udp

我正在开发一个小程序,使用udp通过网络传输字符串命令。我发送的正确字符串被正确接收,但是一个特定的字符串没有完全接收。我不知道它是发送端还是接收端哪个有问题。 正确接收的字符串示例:“connect 123.123.1.1” 未正确接收的字符串:“a / name / 123.123.1.1”收到此消息时收到的内容:“a / name / 123”。 发送代码:

public  void sendToAll(String massage) {
    //send massage to all clients

    byte[] sendData = new byte[1500];
    //clients is a linked list
    for (int i = 0; i < clients.size(); i++) {
        String ip = clients.get(i).ip;
        sendData = massage.getBytes();
        try {
            InetAddress IPAddress = InetAddress.getByName(ip);
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 11222);
            clientSocket.send(sendPacket);
        } catch (Exception e) {

        }
    }
}

接收代码:

byte[] receiveData = new byte[1500];
while (true) {
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      serverSocket.receive(receivePacket);
      String massage = new String(receivePacket.getData());

      //operations for other commands

      if (massage.startsWith("a/")) {

            String[] info = massage.split("/");
            //operations for this command
      }
}

1 个答案:

答案 0 :(得分:0)

虽然我目前不知道你的问题的原因,但我发现你的代码中有一些东西要找,可能其中一个与所有这些的原因有关。 首先,在send方法中,在将字符串命令编码为字节之前,分配大小为1500的sendData缓冲区。它不是必需的,因为方法getBytes()返回一个新的字节数组。但是,这确实不应该引起任何问题。

让我更担心的是接收方法和那一行:

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

根据java api文档,数据包的方法getData()将返回传递给它的缓冲区。该缓冲区长度为1500字节,尝试以这种方式使用String构造函数会导致整个1500字节。它可能应该是:

String massage = new String(receivePacket.getData(), 0, receivePacket.getLength());
相关问题