DatagramPacket to read non-constant sized UDP message
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: DatagramPacket to read non-constant sized UDP message

  1. #1
    Join Date
    Jul 2004
    Posts
    8

    Question DatagramPacket to read non-constant sized UDP message

    Hi,

    I need to receive UDP packages through DatagramPacket.

    Since the message's length is not constant, I need to read the length first.

    I know the protocol definition for this customized package, say,

    -- id 2 bytes
    -- length 2 bytes
    -- body n bytes, (n = length)


    I want to read the length first, then read the whole message (or the rest of the message, ie. the body).

    The question is, after reading the header( first 4 bytes), when I call the readMsg again, should I read the length of the whole message or just the body ? ( Is the header still in the buffer ?)

    I tried, it seems the former one works, but I don't understand why. If the header is still there after being read out, when the buffer will be cleared for the next UDP message ?

    And, what if the sender sends very fast, even faster than the receiver can read. Where will the data that are not read be ?

    Thanks,


    Code:
    	public byte[] readMsg(int num)throws IOException {
    		
    		
    		// create a packet buffer to store data from packets received.
    		byte inBuf[] = new byte[num];
    		DatagramPacket inPkt = new DatagramPacket(inBuf, num);
    
    		// receive the reply from server.
    	
    		
    		dgSocket.receive(inPkt);
    
    	
    		return inPkt.getData();
    	}
    Last edited by wu7up; March 23rd, 2012 at 01:58 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center