Java Reference
In-Depth Information
chapter 4
Beyond the Basics
T he client and server examples in Chapter 2 demonstrate the basic model for program-
ming with sockets in Java. The next step is to apply these concepts in various programming
models, such as multitasking, nonblocking I/O, and broadcasting.
4.1
Multitasking
Our basic TCP echo server from Chapter 2 handles one client at a time. If a client connects
while another is already being serviced, the server will not echo the new client's data until
it has finished with the current client, although the new client will be able to send data as
soon as it connects. This type of server is known as an iterative server . Iterative servers handle
clients sequentially, finishing with one client before servicing the next. They work best for
applications where each client requires a small, bounded amount of server connection time;
however, if the time to handle a client can be long, the wait experienced by subsequent clients
may be unacceptable.
To demonstrate the problem, add a 10-second sleep using Thread.sleep() after the Socket
constructor call in TCPEchoClient.java and experiment with several clients simultaneously
accessing the TCP echo server. Here the sleep operation simulates an operation that takes
significant time, such as slow file or network I/O. Note that a new client must wait for all
already-connected clients to complete before it gets service.
What we need is some way for each connection to proceed independently, without
interfering with other connections. Java threads provide exactly that: a convenient mechanism
allowing servers to handle many clients simultaneously. Using threads, a single application
can work on several tasks concurrently. In our echo server, we can give responsibility for each
client to an independently executing thread. All of the examples we have seen so far consist
of a single thread, which simply executes the main() method.
In this section we describe two approaches to coding concurrent servers , namely, thread-
per-client , where a new thread is spawned to handle each client connection, and thread pool ,
where a fixed, prespawned set of threads work together to handle client connections.
61
 
Search WWH ::




Custom Search