3

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

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

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

感谢所有提示。彼得

4

2 回答 2

1

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

于 2011-01-22T18:27:22.573 回答
0

这对于这个问题来说为时已晚,但可能对像我这样的人有用。

   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();
    }
}
于 2014-03-13T10:13:33.913 回答