Wednesday 12 December 2012

java program to develope chat server using ServerSocket and Socket class.

Client side:-

import java.net.*;
import java.io.*;
class Client
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),8888);
InputStream in=soc.getInputStream();
OutputStream out=soc.getOutputStream();

DataInputStream sin=new DataInputStream(in);
DataOutputStream sout=new DataOutputStream(out);
BufferedReader br=new BufferedReader(new       InputStreamReader(System.in));
String str;
while(true)
{
System.out.println("Server :"+sin.readUTF());
System.out.print("ME :");
str=br.readLine();
sout.writeUTF(str);
sout.flush();
}
}
}
               Server Side:-

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


             class Server
            {
          public static void main(String args[]) throws Exception
                 {
             //*******************************
                 //Remember we are storing Server socket into Socket by calling accept() method

            ServerSocket ss=new ServerSocket(8888);
            Socket soc =ss.accept();
                //*****************
          InputStream in=soc.getInputStream();
                OutputStream out=soc.getOutputStream();

               DataInputStream sin=new DataInputStream(in);
           DataOutputStream sout=new DataOutputStream(out);
             BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

           String str;

             sout.writeUTF("Wel come...Ready to recived you.");

       while(true)
        {
System.out.println("Client :"+sin.readUTF());
System.out.print("ME :");
str=br.readLine();
sout.writeUTF(str);
sout.flush();
      }


}
}


No comments:

Post a Comment