O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Program: A Java Chat Server

This program implements a simple chat server (Example 16-10) that works with the chat applet from Section 15.11. It accepts connections from an arbitrary number of clients; any message sent from one client is broadcast to all clients. In addition to ServerSockets, it demonstrates the use of threads (see Chapter 24). And since there are interactions among clients, this server needs to keep track of all the clients it has at any one time. I use an ArrayList (see Section 7.4) to serve as an expandable list, and am careful to use the synchronized keyword around all accesses to this list to prevent one thread from accessing it while another is modifying it (this is discussed in Chapter 24).

Example 16-10. ChatServer.java

/** Simple Chat Server to go with our Trivial Chat Client. * * Does not implement any form of "anonymous nicknames" - probably * a good thing, given how a few people have abused anonymous * chat rooms in the past. */ public class ChatServer { /** What I call myself in system messages */ protected final static String CHATMASTER_ID = "ChatMaster"; /** What goes between any handle and the message */ protected final static String SEP = ": "; /** The Server Socket */ protected ServerSocket servSock; /** The list of my current clients */ protected ArrayList clients; /** Debugging state */ private boolean DEBUG = false; /** Main just constructs a ChatServer, which should never return */ public static void main(String[] argv) { System.out.println("DarwinSys ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required