Working with UDP DatagramSockets in Java
Difficulty Level : Hard
Last Updated : 04 Jan, 2022
DatagramSockets are Java’s mechanism for network communication via UDP instead of TCP. Java
provides DatagramSocket to communicate over UDP instead of TCP. It is also built on top of IP.
DatagramSockets can be used to both send and receive packets over the Internet.
One of the examples where UDP is preferred over TCP is the live coverage of TV channels. In this aspect,
we want to transmit as many frames to live audience as possible not worrying about the loss of one or
two frames. TCP being a reliable protocol add its own overhead while transmission.
Another example where UDP is preferred is online multiplayer gaming. In games like counter-strike or
call of duty, it is not necessary to relay all the information but the most important ones. It should also be
noted that most of the applications in real life uses careful blend of both UDP and TCP; transmitting the
critical data over TCP and rest of the data via UDP.
This article is a simple implementation of one-sided client-server program wherein the client sends
messages to server and server just prints it until the client sends “bye”.
Java Datagram programming model Steps
Creation of DatagramSocket:- First, a datagramSocket object is created to carry the packet to the
destination and to receive it whenever the server sends any data. To create a datagramSocket following
constructors can be used:
protected DatagramSocket DatagramSocket():
Syntax: public DatagramSocket()
throws SocketException
Creates a datagramSocket and binds it to any available
port on local machine. If this constructor is used, the
OS would assign any port to this socket.
protected DatagramSocket DatagramSocket(int port):-
Syntax: public DatagramSocket(int port)
throws SocketException
Parameters:
port - port to which socket is to be bound
Throws:
SocketException - If the socket cannot be bound to the
specific local port. Creates a DatagramSocket and binds
to the specified port on the local machine.
protected DatagramSocket DatagramSocket(int port, InetAddress inetaddress):-
Syntax: public DatagramSocket(int port,
InetAddress inetaddress)
throws SocketException
Parameters:
port - port to which socket is to be bound.
inetaddress - local address to which socket is to be bound.
Throws:
SocketException - If the socket cannot be bound to the
specific local port. It creates a DatagramSocket and
binds it to specified port and ip-address.
Creation of DatagramPacket: In this step, the packet for sending/receiving data via a datagramSocket is
created.
Constructor to send data: DatagramPacket(byte buf[], int length, InetAddress inetaddress, int port):-
Syntax: public DatagramPacket(byte[] buf,
int offset,
int length,
SocketAddress address)
Parameters:
buf - the packet data.
offset - the packet data offset.
length - the packet data length.
address - the destination socket address.
Constructs a DatagramPacket for sending data at specified address
and specified port.
Constructor to receive the data:
DatagramPacket(byte buf[], int length):-
Syntax: public DatagramPacket(byte buf[],
int length)
Parameters:
buf - the packet data.
length - the packet data length.
Constructs a DatagramPacket for receiving the data of length length
in the byte array buf.
Invoke a send() or receive() call on socket object
Syntax: void send(DatagramPacket packet)
throws SocketException
Parameters:
packet - Datagrampacket to send.
Throws:
SocketException - If there is an error in binding.
IllegalArgumentException - if address is not supported by the socket.
Syntax: void receive(DatagramPacket packet)
throws SocketException
Parameters:
packet - Datagrampacket to receive from this socket.
Throws:
SocketException - If there is an error in binding.
IllegalArgumentException - if address is not supported by the socket.
Client Side Implementation
// Java program to illustrate Client side
// Implementation using DatagramSocket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class udpBaseClient_2
public static void main(String args[]) throws IOException
Scanner sc = new Scanner(System.in);
// Step 1:Create the socket object for
// carrying the data.
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getLocalHost();
byte buf[] = null;
// loop while user not enters "bye"
while (true)
String inp = sc.nextLine();
// convert the String input into the byte array.
buf = inp.getBytes();
// Step 2 : Create the datagramPacket for sending
// the data.
DatagramPacket DpSend =
new DatagramPacket(buf, buf.length, ip, 1234);
// Step 3 : invoke the send call to actually send
// the data.
ds.send(DpSend);
// break the loop if user enters "bye"
if (inp.equals("bye"))
break;
TCP
Client-Side Programming
Establish a Socket Connection
To connect to another machine we need a socket connection. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port. The
java.net.Socket class represents a Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code
will run on the single stand-alone machine).
The second argument – TCP Port. (Just a number representing which application to run on a
server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)
Communication
To communicate over a socket connection, streams are used to both input and output the data.
Closing the connection
The socket connection is closed explicitly once the message to the server is sent.
In the program, the Client keeps reading input from a user and sends it to the server until “Over” is
typed.
Java Implementation
Java
// A Java program for a Client
import java.net.*;
import java.io.*;
public class Client
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
// establish a connection
try
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
catch(UnknownHostException u)
System.out.println(u);
catch(IOException i)
System.out.println(i);
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
try
line = input.readLine();
out.writeUTF(line);
catch(IOException i)
System.out.println(i);
}
}
// close the connection
try
input.close();
out.close();
socket.close();
catch(IOException i)
System.out.println(i);
public static void main(String args[])
Client client = new Client("127.0.0.1", 5000);
Server Programming
Establish a Socket Connection
To write a server application two sockets are needed.
A ServerSocket which waits for the client requests (when a client makes a new Socket())
A plain old Socket socket to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
After finishing, it is important to close the connection by closing t
ocket as well as input/output streams.
Java
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
// starts server and waits for a connection
try
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
try
line = in.readUTF();
System.out.println(line);
catch(IOException i)
System.out.println(i);
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
System.out.println(i);
public static void main(String args[])
Server server = new Server(5000);
Important Points
Server application makes a ServerSocket on a specific port which is 5000. This starts our Server
listening for client requests coming in for port 5000.
Then Server makes a new Socket to communicate with the client.
socket = server.accept()
The accept() method blocks(just sits there) until a client connects to the server.
Then we take input from the socket using getInputStream() method. Our Server keeps receiving
messages until the Client sends “Over”.
After we’re done we close the connection by closing the socket and the input stream.
To run the Client and Server application on your machine, compile both of them. Then first run
the server application and then run the Client application.