Server to Client using UDP Example Java

Server to Client using UDP Example Java

Before going into the details of this program "Server to Client UDP Java", it is advised to go through the network basics, sockets and binding and UDP basics.

The functionality in this application of "Server to Client UDP Java Example" is server sends system time to the client for each second. The client receives and displays. This is used in on-line exams etc.

Example on Server to Client UDP Java

1st Application: Server sending data to Client

Server program –

Date currentDate = new Date( );
String s1 = currentDate.toString( );
byte arr[] = s1.getBytes( );

The DatagramSocket sends data in the form of packets. The Date object is converted into a byte array with getBytes() method of String class.

InetAddress address = InetAddress.getLocalHost( );

The address of the system should be obtained as an object of InetAddress. This is used later to pass to the DatagramPacket constructor.

DatagramPacket dpack = new DatagramPacket(arr, arr.length, address, 2000);

The DatagramPacket constructor takes four parameters. The name of the byte array, how many bytes of the array are to be sent (here complete array is sent, but you can send a part of the array also by giving offset), system address as an object of InetAddress and the port number.


The send() method of DatagramSocket sends datagram packet to the destination. For every 1000 milliseconds (1 second) the time is sent.

Following are the exceptions thrown by the methods

  1. DatagramSocket() throws SocketException
  2. getLocalHost() throws UnknownHostException
  3. sleep() throws InterruptedException
  4. send() throws IOException

Client program –

Server to Client UDP Java
Output Screenshot of Server to Client UDP Java

Leave a Reply

Your email address will not be published. Required fields are marked *