ChatServerpublic 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!! |
Fields Summary |
---|
protected static final String | CHATMASTER_IDWhat I call myself in system messages | protected static final String | SEPWhat goes between any handle and the message | protected ServerSocket | servSockThe Server Socket | protected ArrayList | clientsThe list of my current clients | private static boolean | DEBUGDebugging 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 void | log(java.lang.String s)
System.out.println(s);
| public static void | main(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 void | runServer()
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);
}
|
|