Java program to demonstrate UDP Communication with example of country capital name

Simple java program for UDP Communication where client will send name of country and server will return the capital of that country.

Code:

Server:

package aj.pkg9;

import java.io.*;

import java.net.*;

import java.util.HashMap;

import java.util.Map;



class Server

{

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

{

Map<String, String> map = new HashMap<String,String>();

map.put("INDIA", "DELHI");

map.put("NEPAL", "KATHMANDU");

map.put("SHRI-LANKA", "COLUMBO");

map.put("BANGLADESH", "DHAKA");

map.put("CHINA", "BEIJING");

DatagramSocket serverSocket = new DatagramSocket(1111);

byte[] receiveData = new byte[1024];

byte[] sendData = new byte[1024];

while(true)

{

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

String sentence = new String( receivePacket.getData(),0,5);

InetAddress IPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

String capitalized = sentence.toUpperCase();

String capitalizedSentence = map.get(capitalized);

sendData = capitalizedSentence.getBytes();

DatagramPacket sendPacket =

new DatagramPacket(sendData, sendData.length, IPAddress, port);

serverSocket.send(sendPacket);

}

}

}


Client:


package aj.pkg9;

import java.io.*;

import java.net.*;



class Client

{

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

{

BufferedReader inFromUser =

new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();

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

byte[] sendData = new byte[1024];

byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();

sendData = sentence.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 1111);

clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String modifiedSentence = new String(receivePacket.getData());

System.out.println("FROM SERVER:" + modifiedSentence);

clientSocket.close();

}

}

Comments

Popular posts from this blog

C program to evaluate Prefix Expression using Stack data structure

Java Program to Implement sorting algorithm using TCP on Server application

C++ program to perform data transformation Min-max and Z score Normalization