Creating an Server-Client Application using the DatagramPacket and DatagramSocket classes

To create an application that uses UDP to establish connection between a client and server, we need to perform the following steps:

  • Create a server program
  • Create a client program
  • Execute the client and server program

Let’s perform the steps in the following subsections:

Creating the Server Program



Let’s create the server class, named UDPServerEx which takes massages from a user and sends the messages (datagrams) to the clients. Listing 1 shows the code of the UDPServerEx.java file:

UDPServerEx.java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A server that sends messages to the client
  
import java.net.*;
  
class UDPServerEx {
  
    public static DatagramSocket mySocket;
    public static byte myBuffer[] = new byte[2000];
  
    public static void serverMethod() throws Exception
    {
        int position = 0;
        while (true) {
            int charData = System.in.read();
            switch (charData) {
            case -1:
                System.out.println(
                    "The execution of "
                    + "the server has been terminated");
                return;
            case '\r':
                break;
            case '\n':
                mySocket.send(
                    new DatagramPacket(
                        myBuffer,
                        position,
                        InetAddress.getLocalHost(),
                        777));
                position = 0;
                break;
            default:
                myBuffer[position++]
                    = (byte)charData;
            }
        }
    }
    public static void main(String args[]) throws Exception
    {
        System.out.println("Please enter some text here");
        mySocket = new DatagramSocket(888);
        serverMethod();
    }
}

chevron_right


To compile the UDPServerEx.java file:

D:\UDPExample>javac UDPServerEx.java

Note: The path may vary according to where you save file.

Creating the ClientProgram

Let’s create a client class, named UDPClient, which accepts the messages sent from the server, UDPServerEx class. The client then displays the messages received in the Command Prompt. Listing 2 shows the code of the UDPClient.java file:

UDPClient.java

filter_none

edit
close

play_arrow

link
brightness_4
code

// UDPClient that receives and
// displays messages sent from the server
  
import java.net.*;
class UDPClient {
  
    public static DatagramSocket mySocket;
    public static byte myBuffer[] = new byte[2000];
  
    public static void clientMethod() throws Exception
    {
        while (true) {
            DatagramPacket dataPacket
                = new DatagramPacket(myBuffer,
                                     myBuffer.length);
            mySocket.receive(dataPacket);
            System.out.println("Message Recieved :");
            System.out.println(
                new String(
                    dataPacket.getData(),
                    0,
                    dataPacket.getLength()));
        }
    }
    public static void main(String args[]) throws Exception
    {
        System.out.println(
            "You need to press CTRL+C"
            + " in order to quit.");
        mySocket = new DatagramSocket(777);
        clientMethod();
    }
}

chevron_right


Use the following command to compile the UDPClient.java file:

D:\UDPExample>javac UDPClient.java

Output
Note: To execute the UDPServerEx and UDPClient classes, run the UDPServerEx.java and UDPClient.java in two separate Command Prompt windows. Remember, the UDPServerEx class is executed before the UDPClient class. Figure 1 shows the output of the UDP Server java and UDPClient.java files:

Showing the Output of the UDPServerEx and UDPClient Classes



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.