Answer:
Step-by-step explanation:
UDPServer Implementation :
package in.techdive.udp.server;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* UDP Server listening to receive data from UDP Clients
*/
public class UDPServer
{
public static void main(String args[])
{
int server_port = 1111;
System.out.println("UDP Server Listening in " + server_port);
try
{
// DatagramSocket created and listening in Port 1111
DatagramSocket socket = new DatagramSocket(server_port);
byte[] msgBuffer = new byte[1024];
// DatagramPacket for receiving the incoming data from UDP Client
DatagramPacket packet = new DatagramPacket(msgBuffer, msgBuffer.length);
while (true)
{
socket.receive(packet);
String message = new String(msgBuffer, 0, packet.getLength());
System.out.println("UDPServer: Message received = " + message);
packet.setLength(msgBuffer.length);
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Error in getting the Data from UDP Client");
}
}
}
UDPClient Implementation :
package in.techdive.udp.client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* UDP Client for sending message
*/
public class UDPClient
{
public static void main(String args[])
{
try
{
String server_address = "localhost";
int server_port = 1111;
String message = "Techdive.in";
InetAddress address = InetAddress.getByName(server_address);
// Create Datagram packet with the UDP Server Ipaddress/ Port and Message to be sent
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, address, server_port);
// Create DatagramSocket socket and send the Message
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
System.out.println("UDPClient: Sent data to Server ; Message = " + message);
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Error in sending the Data to UDP Server");
}
}
}
Testing :
In order to test the above UDP Client and Server, perform the below steps,
1. Execute the UDPServer.java class.
This will create the Datagram Socket and it will listen continuously in the port 1111.
2. Execute the UDPClient.java class which will send the data using Datagram Socket to the local host in port 1111.
Output :
UDP Server Listening in 1111
UDPServer: Message received = Techdive.in