开发者

Trimming 0x00 in received DatagramPacket

In my Java app I receive DatagramPacket(s) through DatagramSocket. I know the maximum number of bytes which packet could contain, but actually every packet length varies (not exceeding max length).

Let's assume that MAX_PACKET_LENGTH = 1024 (bytes). So every time DatagramPacket is received it is 1024 bytes long, but not always all bytes contains information. It may happen that开发者_如何学C packet has 10 bytes of useful data, and the rest of 1014 bytes is filled with 0x00.

I am wondering if there is any elegant way to trim this 0x00 (unused) bytes in order to pass to the other layer only useful data? (maybe some java native methods? going in a loop and analysing what packet contains is not desired solution :))

Thanks for all hints. Piotr


You can call getLength on the DatagramPacket to return the ACTUAL length of the packet, which may be less than MAX_PACKET_LENGTH.


This is too late for the question but, could be useful for person like me.

   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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜