Java Reference
In-Depth Information
We set the priority lower on our thread so that the client processing does not
dominate other tasks such as the ServerSocket monitoring of new incoming
clients and the serving of other clients by other Worker objects.
The run() method is, of course, the heart of the thread class and is where
the interaction with the client occurs. Before we discuss possible tasks for the
Worker we look at setting up I/O streams with the client.
14.2.3 I/O with the client
Our thread communicates with the client via the I/O streams made available
by the Socket object. The code snippet from the run() method here in our
ClientProcess shows how to obtain an InputStream from the socket and
then wrap it with an InputStreamReader using the 8859 1 character encoding
and then wrap that with a BufferedReader . (See Chapter 9 for information
about character encodings such as 8859 1.)
... The run() method in Worker ...
public void run () {
try {
// Use the client socket to obtain an input stream.
InputStream socket - in = fClient.getInputStream ();
// For text input we wrap an InputStreamReader around
// the raw input stream and set ASCII character encoding.
InputStreamReader isr =
new InputStreamReader (socket - in, "8859 - 1");
// Finally, use a BufferReader wrapper to obtain
// buffering and higher order read methods.
BufferedReader client - in = new BufferedReader (isr);
...
We then obtain an OutputStream from the socket as shown in the next
code snippet. We wrap this with an OutputStreamWriter and then with a
PrintWriter .
... Continue in the run() method in Worker ...
...
BufferedReader client - in = new BufferedReader (isr);
// Now get an output stream to the client.
OutputStream out = fClient.getOutputStream ();
Search WWH ::




Custom Search