繁体   English   中英

Java Datagramsocket收到不完整的消息

[英]Java datagramsocket receives incomplete message

我正在开发一个小程序,可以使用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
      }
}

尽管我目前尚不知道问题的原因,但我在您的代码中找到了一些需要寻找的东西,也许其中之一与所有这一切的原因有关。 首先,在send方法中,在将字符串命令编码为字节之前,分配大小为1500的sendData缓冲区。 不需要,因为方法getBytes()返回一个新的字节数组。 但是,那确实不会造成任何问题。

更让我担心的是接收方法,以及以下内容:

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

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

String massage = new String(receivePacket.getData(), 0, receivePacket.getLength());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM