Java Reference
In-Depth Information
os
.
close
();
}
}
catch
catch
(
IOException e
) {
System
.
err
.
println
(
e
);
}
}
}
Handling Multiple Clients
Problem
Your server needs to handle multiple clients.
Solution
Use a thread for each.
Discussion
In the C world, several mechanisms allow a server to handle multiple clients. One is to use a
special “system call”
select()
or
poll()
, which notifies the server when any of a set of
file/socket descriptors is ready to read, ready to write, or has an error. By including its ren-
dezvous socket (equivalent to our
ServerSocket
) in this list, the C-based server can read
from any of a number of clients in any order. Java does not provide this call, because it is not
readily implementable on some Java platforms. Instead, Java uses the general-purpose
Thread
mechanism, as described in
Program: Threaded Network Server
.
Threads are, in fact,
one of the other mechanisms available to the C programmer on most platforms. Each time
the code accepts a new connection from the
ServerSocket
, it immediately constructs and
The Java code to implement accepting on a socket is pretty simple, apart from having to
catch
IOException
s:
/** Run the main loop of the Server. */
void runServer( ) {
while (true) {