Java Networking Examples: Client and Server Application in UDP

    UDP(User Datagram Protocol). It is a transport layer protocol which is not a reliable communication. But it suitable for video streaming applications.

Logic:

UDPServer:

  • ·       A DatagramSocket object is created with a port ‘9876’.
  • ·       Data is declared as byte to receive the data packet from client.
  • ·       Server starts receiving packets.
  • ·       Prints the received message in the command prompt.
  • ·       The server stops when it receives the exit message.
  • ·       The server socket is closed.

UDP Client:

  • ·       A datagramSocket is created.
  • ·       IP address of the system is get using getByName() function.
  • ·       Data is declared as byte.
  • ·       Message is created.
  • ·       Data is sent as a datapacket. The datapacket contains the sending data,its length,ip address,port number.
  • ·       After sending the data packet,the socket is closed.

Program implementation:

Client:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPClientEg {

    public static void main(String[] args) throws Exception {

        DatagramSocket cSocket1 = new DatagramSocket();

        InetAddress IPAddress1 = InetAddress.getByName("localhost");

        byte[] sendData1 = new byte[1024];

        String msg = "welcome to the java networking programming";

        sendData1 = msg.getBytes();

        DatagramPacket sPacket = new DatagramPacket(sendData1, sendData1.length, IPAddress1, 9876);

        cSocket1.send(sPacket);

        System.out.println("Message is sent.");

        cSocket1.close();

    }

}

Server:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

public class UDPServerEg {

    public static void main(String[] args) throws Exception {

        DatagramSocket sSocket = new DatagramSocket(9876);

        byte[] recData = new byte[1024];

        while (true) {

            DatagramPacket recPacket = new DatagramPacket(recData, recData.length);

            sSocket.receive(recPacket);

            String msg = new String(recPacket.getData(), 0, recPacket.getLength());

            System.out.println("Received: " + msg);

            if (msg.equals("exit")) {

                System.out.println("Server is going to exit.");

                break;

            }

        }

        sSocket.close();

    }

}

Output:

Client:

C:\raji\blog>javac UDPClientEg.java

C:\raji\blog>java UDPClientEg

Message is sent.

Server:

C:\raji\blog>javac UDPServerEg.java

C:\raji\blog>java UDPServerEg

Received: welcome to the java networking programming

This is a simple client and server implementation using UDP. You can use this code as sample and modify if you need. Keep coding!!!

No comments:

Post a Comment