10 July 2014

Chat software

Here is the server side code for chat software just copy it down and compile and run 


import java.util.*;
import java.net.*;
import java.io.*;
class Server // outer class
{
PrintWriter writer;
ArrayList clientoutputstreams; // an Arraylist in which we keep adding writers of different clients
Socket clientsocket;
void go() // go() method which is called in main() method...
{
clientoutputstreams = new ArrayList();
try
{
ServerSocket ss = new ServerSocket(4000); // creating a Server at port no. 4000
while(true) // an infinite loop for accepting connection requests as
{ // long as the program is running..
clientsocket = ss.accept(); // accept() method which returns a Socket for communication
System.out.println(clientsocket);
System.out.println("clientsocket");
writer = new PrintWriter(clientsocket.getOutputStream());
clientoutputstreams.add(writer);
Thread t = new Thread(new Clienthandler(clientsocket)); // a new Thread object created and the Thread is
t.start(); //  started whenever a request is accepted....
}
}
catch(Exception e)
{e.printStackTrace();}

}
class Clienthandler implements Runnable // an inner class that implements Runnable interface
{ // making it a Thread class
Socket sock;
BufferedReader reader;
public Clienthandler(Socket clientsocket) // constructor of the inner Thread class that takes the
{ // Socket(returned by accept() method) as argument
// and creates a buffered reader for each client..
try
{
InputStreamReader isr = new InputStreamReader(clientsocket.getInputStream());
reader = new BufferedReader(isr);
}
catch(Exception Ex)
{Ex.printStackTrace();}
}

public void run() // the overridden run() method(what happens in
{ // the new Thread)
String message;
try
{
while((message = reader.readLine())  != null) // reads from each client text until it is null
{ // and stores it in String object 'message'
System.out.println(message);
writeToAll(message); // writeToAll() method called...
}
}
catch(Exception f)
{f.printStackTrace();}
}
} // inner class ends...
public void writeToAll(String message) // writeToAll() method takes the read texts
{ // from all clients,i.e.'message' and writes it to
Iterator it = clientoutputstreams.iterator(); // all the connected clients
while(it.hasNext())
{
try
{
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
System.out.print(message);
writer.flush();
}
catch(Exception c)
{c.printStackTrace();}
}
}
public static void main(String[] man) // main() method
{ // creates an object of Server class and calls
Server s = new Server(); // its go() method...
s.go();
}
} // outer class ends...

No comments:

Post a Comment