import java.io.*; 
import java.net.*; 
import java.util.*;
 
public class ChatServer { 
 
    /* The Chatter program    by J M Bishop  January 1997 
     * ===================    Java 1.1 January 1998 
     * Sets up a server for multiple conversations. 
     * 
     * Join in by typing  
     * telnet x y 
     * where x and y are the computer's name and port as 
     * given when the Chatter starts. 
     * 
     * Modified 1998-2006 by bsl, nza
     */ 
 
    private static LinkedList<Socket> clientList = new LinkedList<Socket>(); 
 
    public static void main(String[] args) throws IOException { 
      // Get the port and create a socket there. 
	int port = 8190; 
	ServerSocket listener = new ServerSocket(port); 
	System.out.println("The Chat Server is running on port "+port); 
 
      // Listen for clients. Start a new handler for each. 
      // Add each client to the list. 
	while (true) { 
	    Socket client = listener.accept(); 
	    new ChatHandler(client).start(); 
            System.out.println("New client on client's port "+
			       client.getPort()); 
	    clientList.add(client); 
	} 
    } 
 
    static synchronized void broadcast(String message, String name)  
	    throws IOException { 
	// Sends the message to every client including the sender. 
	Socket s; 
	PrintWriter p; 
	for (int i = 0; i < clientList.size(); i++){ 
	    s = clientList.get(i); 
	    p = new PrintWriter(s.getOutputStream(), true); 
	    p.println(name+": "+message); 
	} 
    } 
 
    static synchronized void remove(Socket s) { 
	clientList.remove(s); 
    }     
} 
 
class ChatHandler extends Thread { 
 
    /* The Chat Handler class is called from the Chat Server: 
     * one thread for each client coming in to chat. 
     */ 
 
    private BufferedReader in; 
    private PrintWriter out; 
    private Socket toClient; 
    private String name; 
 
    ChatHandler(Socket s) { 
	toClient = s; 
    } 
 
    public void run() { 
	try { 
	    /* Create i-o streams through the socket we were given
	     * when the thread was instantiated and welcome the new client. 
	     */ 
 
	    in = new BufferedReader(new InputStreamReader( 
		    toClient.getInputStream())); 
	    out = new PrintWriter(toClient.getOutputStream(), true); 
	    out.println("*** Welcome to the Chatter ***"); 
	    out.println("Type BYE to end"); 
	    out.print("What is your name? ");  
	    out.flush(); 
	    String name = in.readLine(); 
	    ChatServer.broadcast(name+" has joined the discussion.", "Chatter"); 
 
	    // Read lines and send them off for broadcasting. 
	    while (true) { 
		String s = in.readLine();
  		if (s.startsWith("BYE")) {
       	            ChatServer.broadcast(name+" has left the discussion.", 
			    "Chatter"); 
		    break; 
		} 
		ChatServer.broadcast(s, name); 
	    } 
	    ChatServer.remove(toClient); 
	    toClient.close(); 
	} catch (Exception e) { 
	    System.out.println("Chatter error: "+e); 
	} 
    } 
} 
 
 
 


