Java Reference
In-Depth Information
}
}
Program: A Java Chat Server
This program implements a simple chat server (see
Example 16-16
)
that works with the chat
client program from
Program: Chat Client
. It accepts connections from an arbitrary number
of clients; any message sent from one client is broadcast to all clients. In addition to
Server-
Socket
s, it demonstrates the use of threads (see
Chapter 22
). Because 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
Like an Array, but More Dynamic
)
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 22
)
.
Example 16-16. ChatServer.java
public
public class
ChatServer
{
/** What I call myself in system messages */
protected
class
ChatServer
protected final
static
String CHATMASTER_ID
=
"ChatMaster"
;
/** What goes between any handle and the message */
protected
final static
protected final
static
String SEP
=
": "
;
/** The Server Socket */
protected
final static
protected
ServerSocket servSock
;
/** The list of my current clients */
protected
protected
List
<
ChatHandler
>
clients
;
/** Debugging state */
private
private static
static
boolean
boolean
DEBUG
=
false
false
;
/** Main just constructs a ChatServer, which should never return */
public
public static
throws
IOException
{
System
.
out
.
println
(
"DarwinSys ChatServer 0.1 starting..."
);
iif
(
argv
.
length
==
1
&&
argv
[
0
].
equals
(
"-debug"
))
DEBUG
=
true
static
void
void
main
(
String
[]
argv
)
throws
true
;
ChatServer w
=
new
new
ChatServer
();
w
.
runServer
();
// should never return.
System
.
out
.
println
(
"**ERROR* ChatServer 0.1 quitting"
);
}
/** Construct (and run!) a Chat Service
* @throws IOException
*/
ChatServer
()
throws
throws
IOException
{
clients
=
new
new
ArrayList
<>();