Communication Between Server And Client Programs Using UDP In Java

LEVEL: Intermediate

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code


There are two programs. One is Server-side and another is Client-side. Both programs communicate with each other using UDP (User Datagram Protocol) and DatagramSocket class of Java networking API.

1) UdpServer.java : This is Server-side program. It creates DatagramSocket on specified port number.  Whenever any DatagramPacket is sent for this port number and destination address, it can be received by this socket.

The Server-side program needs to be run first. Client’s socket sends datagram-packet for this Server.

2) UdpClient.java : This is Client-side program. It creates DatagramSocket on specified port number.  Whenever any DatagramPacket is sent for this port number and destination address, it can be received by this socket.  Server’s socket sends datagram-packet for this Client.

While running both program pass the destination address as ‘IP Address/host-name’  from command-line argument.

First of all Server sends message to Client and then Client sends message to Client. Both programs can communicate and sends & receives messages one by one. Send message as ‘exit’ to stop the communication.

To run Server-side program: java UdpServer <IPAddress/host-name>

To run Client-side program: java UdpClient <IPAddress/host-name>