Create two class Client & Server for communication using udp connection in java
import java.net.*;
import java.util.*;
public class UDPServer
{
public static void main(String[] args)throws Exception
{
DatagramSocket mysocket=new DatagramSocket(5958);
byte myBuffer[];
while(true)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the message :");
String msg =sc.nextLine();
myBuffer=msg.getBytes();
DatagramPacket mypack=new DatagramPacket(myBuffer,myBuffer.length,InetAddress.getByName("localhost"),5959);
mysocket.send(mypack);
if(msg.equals("exit"))
{
break;
}
}
}
}
import java.net.*;
public class UDPClient {
public static void main(String[] args)throws Exception {
DatagramSocket mysocket=new DatagramSocket(5959);
byte mybuffer[]=new byte[2000];
while(true)
{
DatagramPacket datapack=new DatagramPacket(mybuffer,mybuffer.length);
mysocket.receive(datapack);
String msg=new String(datapack.getData(),0,datapack.getLength());
System.out.println("Message Received:-"+msg);
if(msg.equals("exit"))
{
break;
}
}
}
}
Output
Server's Output
Client's Output
0 comments:
Post a Comment