FileDocCategorySizeDatePackage
ChatServer.javaAPI DocExample6533Sat Mar 13 15:56:32 GMT 2004chat

ChatServer

public class ChatServer extends Object
Trivial Chat Server to go with our Trivial Chat Client. WARNING -- this code is believed thread-safe but has NOT been 100% vetted by a team of world-class experts for Thread-safeness. DO NOT BUILD ANYTHING CRITICAL BASED ON THIS until you have done so. See the various books on Threaded Java for design issues.
author
Ian F. Darwin, http://www.darwinsys.com/
version
$Id: ChatServer.java,v 1.10 2004/03/13 21:56:32 ian Exp $

Fields Summary
protected static final String
CHATMASTER_ID
What I call myself in system messages
protected static final String
SEP
What goes between any handle and the message
protected ServerSocket
servSock
The Server Socket
protected ArrayList
clients
The list of my current clients
private static boolean
DEBUG
Debugging state
Constructors Summary
ChatServer()
Construct (and run!) a Chat Service

		clients = new ArrayList();
		try {
			servSock = new ServerSocket(Chat.PORTNUM);
			System.out.println("DarwinSys Chat Server Listening on port " +
				Chat.PORTNUM);
		} catch(IOException e) {
			log("IO Exception in ChatServer.<init>" + e);
			System.exit(0);
		}
	
Methods Summary
protected voidlog(java.lang.String s)

		System.out.println(s);
	
public static voidmain(java.lang.String[] argv)
Main just constructs a ChatServer, which should never return


	          
	     
		System.out.println("DarwinSys Chat Server 0.1 starting...");
		if (argv.length == 1 && argv[0].equals("-debug"))
			DEBUG = true;
		ChatServer w = new ChatServer();
		w.runServer();			// should never return.
		System.out.println("**ERROR* Chat Server 0.1 quitting");
	
public voidrunServer()

		try {
			while (true) {
				Socket us = servSock.accept();
				String hostName = us.getInetAddress().getHostName();
				System.out.println("Accepted from " + hostName);
				ChatHandler cl = new ChatHandler(us, hostName);
				synchronized (clients) {
					clients.add(cl);
					cl.start();
					if (clients.size() == 1)
						cl.send(CHATMASTER_ID, "Welcome! you're the first one here");
					else {
						cl.send(CHATMASTER_ID, "Welcome! you're the latest of " +
							clients.size() + " users.");
					}
				}
			}
		} catch(IOException e) {
			log("IO Exception in runServer: " + e);
			System.exit(0);
		}