Our Worker
communicates with the client via the I/O streams created with
the Socket
object. From Chapter
9: Java I/O we learned about streams and how you can obtained
inhanced functionality by wrapping
higher level streams around a basic level stream.
We first create out input stream 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.)
/**
Threaded process to serve the client connected to the
socket.**/
class Worker extends Thread {
Socket fClient;
...
}
public void run () {
try {
// Use the client
socket to obtain an input stream from it.
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.
...
//
Now get an output stream to the client.
OutputStream client_out
= fClient.getOutputStream ();
// For text output
we wrap an OutputStreamWriter around
// the raw output
stream and set ASCII character encoding.
OutputStreamWriter
osr =
new OutputStreamWriter
(client_out, "8859_1");
// Finally, we use
a PrintWriter wrapper to obtain its
// higher level output
methods.
// Open in append
mode.
PrintWriter pw_client_out
= new PrintWriter (osr, true);
....
|
At this point in the code we have streams for both
input and output communications with the client, but we yet discussed
what exactly it is that they they will communicate. The client
can place arbitrary bytes on the stream and the server will see
them, but unless some agreement is made about what form those
bytes should take and what they mean, the communication that happens
is rather meaningless.
In other words, we need to develop some sort of
protocol so that the server and the client can understand
each other. We next discuss the appropriate HTTP
protocol.
References & Web
Resources
Latest update: Dec. 9, 2004