【问题标题】:Trimming 0x00 in received DatagramPacket在收到的 DatagramPacket 中修整 0x00
【发布时间】:2014-03-13 18:13:33
【问题描述】:

在我的 Java 应用程序中,我通过 DatagramSocket 接收 DatagramPacket。我知道数据包可以包含的最大字节数,但实际上每个数据包的长度都不同(不超过最大长度)。

假设 MAX_PACKET_LENGTH = 1024(字节)。因此,每次接收到 DatagramPacket 时,它都是 1024 字节长,但并非所有字节都包含信息。可能会发生数据包有 10 个字节的有用数据,其余 1014 个字节用 0x00 填充。

我想知道是否有任何优雅的方法来修剪这个 0x00(未使用)字节以便只将有用的数据传递给另一层? (也许是一些 java 本地方法?进入循环并分析数据包包含的内容不是我们想要的解决方案 :))

感谢所有提示。 彼得

【问题讨论】:

    标签: trim datagram


    【解决方案1】:

    您可以在 DatagramPacket 上调用 getLength 以返回数据包的实际长度,该长度可能小于 MAX_PACKET_LENGTH。

    【讨论】:

    • 恐怕它没有返回数据包的实际长度。以下代码:int LENGTH = 887; DatagramPacket p = new DatagramPacket(新字节[LENGTH], LENGTH); System.out.println(p.getLength());将打印出 887
    • 它打印出 887 因为 887 是数据包的长度(构造函数的第三个参数)。这可能小于缓冲区的大小(您的示例中的第一个 LENGTH),但在您的情况下它不是
    【解决方案2】:

    这个问题太迟了,但对像我这样的人可能有用。

       private int bufferSize = 1024;
    /**
     * Sending the reply. 
     */
    public void sendReply() {
        DatagramPacket qPacket = null;
        DatagramPacket reply = null;
        int port = 8002;
        try {
            // Send reply.
            if (qPacket != null) {
                byte[] tmpBuffer = new byte[bufferSize];
                                System.arraycopy(buffer, 0, tmpBuffer, 0, bufferSize);
                reply = new DatagramPacket(tmpBuffer, tmpBuffer.length,
                        qPacket.getAddress(), port);
                socket.send(reply);
    
            }
    
        }  catch (Exception e) {
            logger.error(" Could not able to recieve packet."
                    + e.fillInStackTrace());
    
        }
    }
    /**
     * Receives the UDP ping request. 
     */
    public void recievePacket() {
        DatagramPacket dPacket = null;
        byte[] buf = new byte[bufferSize];
        try {
    
            while (true) {
                dPacket = new DatagramPacket(buf, buf.length);
                socket.receive(dPacket);
                // This is a global variable.
                bufferSize = dPacket.getLength();
    
                sendReply();
    
            }
    
        } catch (Exception e) {
            logger.error(" Could not able to recieve packet." + e.fillInStackTrace());
        } finally {
            if (socket != null)
                socket.close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 2013-12-27
      • 2013-01-03
      • 2013-02-09
      相关资源
      最近更新 更多