UDP Protocol | Data Communication and Networking | Example
Client
import java.util.*;
import java.io.*;
import java.net.*;
class Q2_Client{
public static void main(String[] args) throws Exception {
Scanner scan=new Scanner(System.in);
DatagramSocket cSocket=new DatagramSocket();
InetAddress iPAddress=InetAddress.getByName("localhost");
byte[] sdata=new byte[1024];
byte[] rdata=new byte[1024];
System.out.println("\nEnter Number : ");
int st=scan.nextInt();
String s=String.valueOf(st);
sdata=s.getBytes();
DatagramPacket sPacket=new DatagramPacket(sdata, sdata.length, iPAddress, 0614);
cSocket.send(sPacket);
DatagramPacket rPacket=new DatagramPacket(rdata, rdata.length);
cSocket.receive(rPacket);
String mst=new String(rPacket.getData());
System.out.println("\nCube of "+st+" is: "+mst);
cSocket.close();
scan.close();
}
}
Server
import java.io.*;
import java.net.*;
class Q2_Server {
public static void main(String[] args) throws Exception {
DatagramSocket sSocket=new DatagramSocket(0614);
byte[] sdata=new byte[1024];
byte[] rdata=new byte[1024];
while(true){
DatagramPacket sPacket=new DatagramPacket(rdata, rdata.length);
sSocket.receive(sPacket);
String str=new String(sPacket.getData());
System.out.println("\nConnection Established!!");
//System.out.println("\nSending Data : "+cube);
int cube=Integer.parseInt(str.trim());
cube=cube*cube*cube;
str=Integer.toString(cube);
InetAddress iAddress=sPacket.getAddress();
int port =sPacket.getPort();
System.out.println("\nSending Data : "+cube);
sdata=str.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sdata, sdata.length, iAddress, port);
sSocket.send(sendPacket);
}
}
}
Output
Prime Number Using TCP Protocol
Comment your views on this Article :)
No comments
Comment your views on this article