View RSS Feed

Java Socket

Receiving Data via a DatagramSocket

Rate this Entry
by , 04-25-2012 at 11:37 PM (4780 Views)
Data is received through a DatagramSocket by creation of the DatagramPacket firstly & then by receiving data through DatagramSocket receiver() method into it. Example is as following:
Java Code:
DatagramSocket datagramSocket = new DatagramSocket(80);
byte[] buffer = new byte[10];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
Way of instantiation of the DatagramSocket shall be noticed along with the parameter value 80 that has been passed to the constructor. Such parameter is the port of the UDP where DatagramSocket would receive the UDP packets. It has also been mentioned before that UDP and TCP ports are not similar and hence they would not be overlapping. Different processes listening could be there at both UDP & TCP port 80, with no conflict.

Second thing is the creation of DatagramPacket and a byte buffer. It shall be noticed that there is no information present in DatagramPacket regarding node by which data could be sent, as it is usually done while DatagramPacket is created to send the data. Reason is that DatagramPacket will be used to receive data, not to send it. Hence destination address is not required.

Finally, call DatagramSocket's receive() method. This method gets blocked till a DatagramPacket is received.

Received data will be present in the byte buffer of the DatagramPacket. Get buffer by calling:
Java Code:
byte[] buffer = packet.getData();

Submit "Receiving Data via a DatagramSocket" to Facebook Submit "Receiving Data via a DatagramSocket" to Digg Submit "Receiving Data via a DatagramSocket" to Submit "Receiving Data via a DatagramSocket" to StumbleUpon Submit "Receiving Data via a DatagramSocket" to Google