UDP in Java
by, 04-25-2012 at 11:44 PM (1711 Views)
Implementation of UDP has been divided into 2 classes which are: DatagramSocket & DatagramPacket. Data is received by the DatagramSocket through bound port and is placed in DatagramPacket. Packet contains all the required information that one may need to know regarding datagram. Connection concepts donít exist is UDP and hence it just knows regarding single datagrams. Listen at the socket and obtain DatagramPacket.
Datagramís data size is 65.536 bytes(minus 8 bytes) for header. Data size also gets affected due to the underlying IP header size. There is no need to think about big sizes because majority of operating systemís lower level implementations just permit maximum 8.192 bytes/datagram maximum. Generally, it is a great practice to not to deal with those datagrams which are more than 8.192 bytes.
UDP packets are received by creating DatagramSocket, at which listening is done:
Now create a DatagramPacket that will hold the received packet in a byte array:Java Code:import java.net.*; import java.io.*; // ... port = 12000 DatagramSocket serverSocket = new DatagramSocket(port);
Hence UDP packets of 4096 bytes would be allowed to receive.Java Code:byte buffer = new byte; // It is a good idea to store the maximum buffer size as a constant somewhere DatagramPacket packet = new DatagramPacket(buffer, buffer.length)