Receiving Data via a DatagramSocket
by , 04-25-2012 at 10:37 PM (2291 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:
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.Java Code:DatagramSocket datagramSocket = new DatagramSocket(80); byte[] buffer = new byte[10]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datagramSocket.receive(packet);
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();









Email Blog Entry
License4J 4.0
05-22-2013, 12:23 AM in Java Software