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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access