In this discussion, we continue the discussion of the Java client/server architecture begun in the earlier tutorial. Specifically, we will look at a multi-threaded server and client.
The relevant classes are contained in the
java.lang
and the java.net packages. In particular, look at theThread
class, theRunnable
interface, and the Socket and ServerSocket classes.The discussion here is based on Java version 1.1.
If you wish to run the applications discussed here, you may do so using the code included in the programs directory stored with this tutorial.
Multi-Threaded Client and Server
The discussions that follow extend the client and server programs discussed in the Java Clients and Servers I tutorial.
The first goal is to make the client multi-threaded so that it runs the user interface with one thread and handles the I/O with the server in a separate thread.
A second goal is to make the server multi-threaded. It handles the user interface with one thread. A second thread listens on a well-known port for client connections. A third thread is started when a client connection is made to handle that client's requests. After launching the thread to handle a client's connection, the server continues listening for additional client connections. If another connection comes in while an earlier client is being served, a fourth thread is started to handle the new client's requests, etc. Thus, the server includes at least three threads but may start additional threads for multiple simultaneous connections.
Server
Client Application
Client Applet
References
References useful for this discussion include the following:
- Sun's Java Development Kit (JDK)
- Sun's Java API
- Java API Class Hierarchy
- Source