TCP socket is connection-oriented and is based on streams. A socket based on UDP is connectionless and is based on datagrams.
The chunk of data that is sent using UDP is called a datagram or a UDP packet. Each UDP packet has the data, the destination IP address, and the destination port number.
The connectionless socket do not establish a connection before they communicate.
UDP is an unreliable protocol because it does not guarantee the delivery and the order of arrived packets.
In a connectionless protocol, UDP, there will not be a server socket.
In UDP connection, client and server sends or receives a chunk of data without any prior knowledge of communication between them.
Each chunk of data sent to the same destination is independent of the previously sent data.
The following two classes are used when coding a UDP connection.
DatagramPacketclass represents a UDP datagram.
DatagramSocketclass represents a UDP socket that is used to send or receive a datagram packet.
The following code shows how to create a UDP Socket bound to a port number 12345 at localhost.
DatagramSocket udpSocket = new DatagramSocket(12345, "localhost");
DatagramSocket class provides a bind() method,
which lets you bind the socket to a local IP address and a local port number.
A DatagramPacket contains three things:
Constructors of the DatagramPacket class to create a packet to receive data are as follows:
DatagramPacket(byte buf, int length) DatagramPacket(byte buf, int offset, int length)
Constructors of the DatagramPacket class to create a packet to send data are as follows:
DatagramPacket(byte buf, int length, InetAddress address, int port) DatagramPacket(byte buf, int offset, int length, InetAddress address, int port) DatagramPacket(byte buf, int length, SocketAddress address) DatagramPacket(byte buf, int offset, int length, SocketAddress address)
The following code demonstrates how to create a datagram packet:
The following code creates a packet to receive 1024 bytes of data.
byte data = new byte; DatagramPacket packet = new DatagramPacket(data, data.length);
The following code creates a packet that has buffer size of 1024, and receive data starting at offset 8 and it will receive only 32 bytes of data.
byte data2 = new byte; DatagramPacket packet2 = new DatagramPacket(data2, 8, 32);
Data in the packet always has offset and length specified. We need to use offset and length to read the data from a packet.