Thursday, 7 May 2015

UDP CHAT SERVER



CLIENT

import java.net.*;
import java.io.*;

class DatagramClient
{
public static DatagramSocket serversocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;

public static void main(String args[])throws IOException
{
serversocket=new DatagramSocket(clientport);
dp=new DatagramPacket(buffer,buffer.length);
dis=new BufferedReader(new InputStreamReader(System.in));
ia=InetAddress.getLocalHost();
System.out.println(“client is running\ntype’end’ to quit”);

while(true);
{
String str=dis.readLine();
if(str.equals(“end”))
{
System.out.println(“terminated”);
buffer=str.getBytes();
serversocket.send(new DatagramPacket(buffer,str.length(),ia,serverport));
break;
}
buffer=str.getBytes();
serversocket.send(new DatagramPacket(buffer,str.length(),ia,serverport);
serversocket.receive(dp);
String psx=new String(dp.getData(),0,dp.getLength());
System.out.println(“server:”+psx);
}
}
}




SERVER

import java.net.*;
import java.io.*;

class DatagramServer
{
public static DatagramSocket serversocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;

public static void main(String args[])throws IOException
{
serversocket=new DatagramSocket(clientport);
dp=new DatagramPacket(buffer,buffer.length);
dis=new BufferedReader(new InputStreamReader(System.in));
ia=InetAddress.getLocalHost();
System.out.println(“client is running\ntype’end’ to quit”);

while(true);
{
serversocket.receive(dp);
String psx=new String(dp.getData(),0,dp.getLength());
if(psx.equals(“end”))
{
System.out.println(“client:”+psx);
String str=dis.readLine();
buffer=str.getBytes();
serversocket.send(new DatagramPacket(buffer,str.length(),ia,clientport));
}
}
}




No comments:

Post a Comment