Multithreaded Chat Server Example
A) Chat Server
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.Vector;
import java.util.Enumeration;
public class ChatServer{
/* Instance variables declared as static are, essentially, global variables. When objects of
its class are declared, no copy of a static variable is made. Instead, all instances of the
class share the same static variable. */
private static ServerSocket serversock;
private static int port = 1234;
private static Socket clientsock;
/***** main() *****/
public static void main(String args[]) throws IOException{
System.out.println("\n *** ChatServer ***\n");
System.out.println("Server Opening port "+port+" ...\n");
try{
/*Creating a 'ServerSocket' object */
serversock = new ServerSocket(port);
}
catch(IOException ioe){
System.out.println("IOException occuted : "+ioe);
System.exit(1);
}
System.out.println("Server Lisening to port: "+port+"...\n");
do{
clientsock = serversock.accept();
System.out.println("\n<<<<>>>>\n");
ClientHandler handler = new ClientHandler(clientsock);
handler.start();
}while(true);
}//main end
}//Class ChatServer end
/***** ClientHandler class *****/
class ClientHandler extends Thread{
private Socket clientsock;
private ServerSocket serversock;
Scanner input;
PrintWriter output;
/* static variable for save all client objects connected to the Server */
protected static Vector handler = new Vector();
/***** Constructor *****/
public ClientHandler(Socket socket){
clientsock = socket;
/*'Printwriter' and 'Scanner' objects for sending and receiving data from client.
The 'Scanner' object at the client end will receive messages sent by the 'PrintWriter'
object at the server end, while the 'PrintWriter' object at the client end will send
messages that are received by the 'Scanner' object at the server end (using methods
'nextLine' and 'println' respectively).Supplying the PrintWriter constructor with a
second argument of true will cause the output buffer to be flushed for every call of
println (which is usually desirable).*/
try{
input = new Scanner(clientsock.getInputStream());
output = new PrintWriter(clientsock.getOutputStream(),true);
}
catch(IOException ioe){
System.out.println("IOException occuted : "+ioe);
System.exit(1);
}
}//constructor end
/***** run() Method *****/
public void run(){
String name = null;
String message =null;
/* Adding client object(object of ClientHandler) to Vector variable */
handler.addElement(this);
/*
handler.addElement(this);
or
//handler.addElement(new ClientHandler(clientsock));
or
ClientHandler cli = new ClientHandler(clientsock);
handler.addElement(cli);
*/
/* sending message to client //"don't use \n with object 'output',it will cause error"*/
output.println("Enter Your Name :");
/* Server waiting for the 'UserName' from the client */
System.out.println("Server waiting-1 for Message 'UserName' from Client");
name = input.nextLine();
/* sending message to client //"don't use \n with object output,it will cause error"*/
System.out.println("Server sending
output.println("*** WELCOME *** "+name);
/* Printing message in Server */
System.out.println("New User * "+name+" * Logged In");
System.out.println("Server sending
/* broadcasting message to all clients */
broadcast("New User * "+name+" * Logged In");
/* Server waiting for the Message from the client */
System.out.println("Server waiting-2 for Message from client User: "+name);
message = input.nextLine();
while(!message.equals("CLOSE"))
{
/* Printing messages from the client in Server */
System.out.println(name+": "+message);
/* broadcasting message to all clients */
broadcast(name+": "+message);
/* sending message to client */
//broadcast(name+": "+message);
/* Server waiting for the Message from the client */
System.out.println("(
message = input.nextLine();
}
try{
/* Printing a message in Server */
System.out.println("User * "+name+" * Logged Out");
/* broadcasting message to all clients */
broadcast("User * "+name+" * Logged Out");
clientsock.close();
}
catch(IOException ioe){
System.out.println("IOException occuted : "+ioe);
System.exit(1);
}
}//run() end
/*** Method for broadcasting message to all clients ***/
private void broadcast(String message){
Enumeration e = handler.elements();
while(e.hasMoreElements())
{
ClientHandler ch = (ClientHandler)e.nextElement();
/* for broadcasting messages to all Clients except one(this Client). */
if(ch!=this){
ch.output.println(message);
}
}//while
}//broadcast() end
}// Class ClientHandler end.
/* When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object. You can declare both methods and variables to be static. */
/* All of the static statements(including staic blocks) are run(executed) only once,when your program
begins execution (or,more precisely, when its class is first loaded).*/
**********************************************************************
B) Chat Client
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient{
/* Instance variables declared as static are, essentially, global variables. When objects of
its class are declared, no copy of a static variable is made. Instead, all instances of the
class share the same static variable. */
private static int port = 1234;
/*** main() ***/
public static void main(String args[]){
System.out.println("\n *** ChatClient *** \n");
accessServer();
}//main end
/*** accessServer() ***/
/* private static method means you can not invoke the method from
outside the class as the method is private to the class. */
/* Methods declared as static have several restrictions:
1.They can only call other static methods.
2.They must only access static data.
3.They cannot refer to this or super in any way.
A static method can access only the static features, static methods,
and static variables of its parent class. */
private static void accessServer(){
Socket clientsock = null;
try{
clientsock = new Socket("localhost",port);
/*The 'Scanner' object at the client end will receive messages sent by the 'PrintWriter'
object at the server end, while the 'PrintWriter' object at the client end will send
messages that are received by the 'Scanner' object at the server end (using methods
'nextLine' and 'println' respectively).Supplying the PrintWriter constructor with a
second argument of true will cause the output buffer to be flushed for every call of
println (which is usually desirable).*/
Scanner input = new Scanner(clientsock.getInputStream());
PrintWriter output = new PrintWriter(clientsock.getOutputStream(),true);
/*client program will need to set up an input stream
(as another Scanner object) to accept user messages from the keyboard.*/
Scanner userEntry = new Scanner(System.in);
String message,response="dd";
/*Client receiving response messages 'Enter Your name' from the Server and printing it*/
//System.out.println("Client waiting1 for Server response message
response = input.nextLine();
System.out.println(response);
/* Client Accepting 'UserName' from the keyboard and sending message to Server*/
//System.out.println("Client waiting for keyboard Input-1 UserName:");
message = userEntry.nextLine();
output.println(message);
//********************
/* Thread for manage messages from the keyBoard (Sending Messages to Server)*/
KeyBo k = new KeyBo(clientsock,output);
k.start();
/* Thread for manage messages from the Server (Receiving Messages from Server) */
SerM s = new SerM(clientsock,input,output);
s.start();
//********************
///System.out.println("Closing Connection\n");
//clientsock.close();
}
catch(IOException ioe){
System.out.println("IOException occured: "+ioe);
}//try
}//accessServer()end.
}
/* Thread for manage messages from the keyBoard (Sending Messages)*/
class KeyBo extends Thread{
private Socket clientsock;
private Scanner userEntry;
private PrintWriter output;
private String message;
//Constructor
public KeyBo(Socket socket,PrintWriter output){
this.clientsock=socket;;
this.output = output;
this.userEntry = new Scanner(System.in);
}
public void run(){
do{
try{
/* Client Accepting user messages from the keyboard*/
//System.out.println("Enter Your Message: ");
message = userEntry.nextLine();
/*sending messages to the Server*/
output.println(message);
}catch(Exception e){}
}while(!message.equals("CLOSE"));
}//run() end
}// class KeyBo
/* Thread for manage messages from the Server (Receiving Messages) */
class SerM extends Thread{
private Socket clientsock;
private Scanner input;
private PrintWriter output;
private String response;
//Constructor
public SerM(Socket socket,Scanner input,PrintWriter output){
this.clientsock=socket;
this.input = input;
this.output = output;
}
public void run(){
/*Client waiting for receiving response messages from the Server*/
//System.out.println("(Thread 'SerM'
response=input.nextLine();
while(response!=null)
{
/* printing response in client*/
System.out.println(response);
//System.out.println("(Thread 'SerM'
response=input.nextLine();
}//while
}//run
}// class SerM
ChatServer without Multithread.
By SAJU.M
****************************************************************************
No comments:
Post a Comment