FileDocCategorySizeDatePackage
ChatServer.javaAPI DocExample6759Tue Dec 25 20:04:08 GMT 2001None

ChatServer

public class ChatServer extends Object
Trivial Chat Server to go with our Trivial Chat Client. Does not implement any form of "anonymous nicknames" - this is a good thing, given how a few people have abused anonymous chat rooms in the past. 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. YOU HAVE BEEN WARNED!!
author
Ian F. Darwin, ian@darwinsys.com
version
$Id: ChatServer.java,v 1.6 2001/12/26 01:04:09 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>");
			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);
		}