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:
To compile the UDPServerEx.java file:
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:
Use the following command to compile the UDPClient.java file:
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:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.