-----------------------------------------------Client------------------------------------------------------------------
import java.io.*;
import java.net.*;
public class UDP_client {
public static void main(String[] args) throws IOException {
DatagramSocket SrvSoc=new DatagramSocket();
byte[] SData=new byte[1024];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server ready");
while(true)
{
System.out.println("Message to server:");
String srvmsg=br.readLine();
InetAddress IPAddr=InetAddress.getByName(IP of Network);
SData=srvmsg.getBytes();
DatagramPacket SPack=new DatagramPacket(SData,SData.length,IPAddr,4489);
SrvSoc.send(SPack);
byte[] RData=new byte[1024];
DatagramPacket RPack=new DatagramPacket(RData,RData.length);
SrvSoc.receive(RPack);
//System.out.println(RPack.getPort());
String Text=new String(RPack.getData());
if(Text.trim().length()==0)
break;
System.out.println("\nFrom server <<"+Text);
}
System.out.println("\n Client quits \n");
SrvSoc.close();
}
}
------------------------------------------------------------Server----------------------------------------------------
import java.io.*;
import java.net.*;
public class UDP_server {
public static void main(String[] args) throws IOException {
DatagramSocket SrvSoc=new DatagramSocket(port number);
byte[] SData=new byte[1024];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server ready");
while(true)
{
byte[] RData=new byte[1024];
DatagramPacket RPack=new DatagramPacket(RData,RData.length);
SrvSoc.receive(RPack);
//System.out.println(RPack.getPort());
String Text=new String(RPack.getData());
if(Text.trim().length()==0)
break;
System.out.println("\nFrom Client <<"+Text);
System.out.println("Message to client:");
String srvmsg=br.readLine();
InetAddress IPAddr=RPack.getAddress();
SData=srvmsg.getBytes();
DatagramPacket SPack=new DatagramPacket(SData,SData.length,IPAddr,RPack.getPort());
SrvSoc.send(SPack);
}
System.out.println("\n Client quits \n");
SrvSoc.close();
}
}
No comments:
Post a Comment