Unit 1 – Java Networking
Socket Programming (UDP)
UDP Protoocol
The User Datagram Protocol (UDP) is an alternative transport layer protocol for sending data
over IP that is very quick, but not reliable. When you send UDP data, you have no way of
knowing whether it arrived, much less whether different pieces of data arrived in the order in
which you sent them. However, the pieces that do arrive generally arrive quickly.
Java’s implementation of UDP is split into two classes: DatagramPacket and Datagram
Socket.
• The DatagramPacket class stuffs bytes of data into UDP packets called datagrams and
lets you unstuff datagrams that you receive.
• A DatagramSocket sends as well as receives UDP datagrams.
• To send data, you put the data in a DatagramPacket and send the packet using a
DatagramSocket. To receive data, you take a DatagramPacket object from a
DatagramSocket and then inspect the contents of the packet.
• The sockets themselves are very simple creatures. In UDP, everything about a datagram,
including the address to which it is directed, is included in the packet itself; the socket
only needs to know the local port on which to listen or send.
UDP Based Client / Server Socket Programming
UDP Client
import [Link].*;
import [Link].*;
import [Link];
public class UDPClient {
public static void main(String[] args) throws IOException {
DatagramPacket sendPacket;
byte[] sendData;
DatagramSocket clientSocket = new DatagramSocket();
Scanner input = new Scanner([Link]);
while (true) {
String cmd = [Link]();
if ([Link]("QUIT"))
{
[Link]();
[Link](1);
}
sendData = [Link]();
sendPacket = new DatagramPacket(sendData, [Link],
[Link]("[Link]"), 5000);
[Link](sendPacket);
}
}
}
UDP Server
import [Link].*;
import [Link].*;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket serverSocket = new DatagramSocket(5000);
[Link]("Server Started. Listening for Clients on port 5000" + "...");
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket;
while (true) {
receivePacket = new DatagramPacket(receiveData, [Link]);
[Link](receivePacket);
InetAddress IPAddress = [Link]();
int port = [Link]();
String clientMessage = new String([Link](),0,[Link]());
[Link](IPAddress + " ,Port: " + port +"] " + clientMessage);
}
}
}
Output
E:\2024-25\AJP>java UDPClient
hi
E:\2024-25\AJP>java UDPServer
Server Started. Listening for Clients on port 5000...
/[Link] ,Port: 64252] hi
Client Side program - Explanation
• Create DatagramPacket and byte array: A DatagramPacket is a container that holds data
to be sent or received over a UDP connection. A byte array named sendData is created
to hold the message to be sent.
• Create DatagramSocket: A DatagramSocket is established for the client. It acts as the
endpoint for sending and receiving datagrams (packets) on a UDP connection.
• Set Socket Timeout: The setSoTimeout method sets a timeout value (1 second) for the
socket. If no data is received within this time, a SocketTimeoutException is thrown.
• Start User Input Loop: The code enters an infinite loop where the user can input
messages to be sent to the server. If the user inputs “QUIT,” the client socket is closed,
and the program exits.
• Convert String to Bytes: The user input message (cmd) is converted to bytes using
the getBytes() method.
• Create DatagramPacket: A new DatagramPacket is created with the message bytes,
destination IP address ("[Link]"), and port number (5001).
• Send DatagramPacket: The send method of the client socket is used to send the
datagram packet to the server.
ServerSide program - Explanation
• Create DatagramSocket: The UDP server creates a DatagramSocket on port 5001,
indicating that it's ready to listen for incoming datagrams.
• Start Listening Loop: The server enters an infinite loop where it continuously listens
for incoming datagrams.
• Receive DatagramPacket: The receive method of the DatagramSocket waits until a
datagram packet is received. The received data is stored in the receiveData byte array.
• Extract Client Details: The DatagramPacket contains the client's IP address and port.
These details are extracted using the getAddress() and getPort() methods.
• Convert Bytes to String: The received data is converted from bytes to a string using
the String constructor.
• Display Message with Log Header: The server displays the received message along
with a log header that includes a timestamp, client IP address, and port.