Java Reference
In-Depth Information
32
while ((bytesRead = in.read(buffer)) != −1)
33
out.write(buffer, 0, bytesRead);
34
35
out.finish();
// Flush bytes from GZIPOutputStream
36
} catch (IOException e) {
37
logger.writeEntry("Exception="+ e.getMessage());
38
}
39
40
try { // Close socket
41
clntSock.close();
42
} catch (IOException e) {
43
entry.add("Exception="+ e.getMessage());
44
}
45
46
logger.writeEntry(entry);
47
}
48
}
CompressProtocolFactory.java
1.
Factory method for compression protocol:
lines 9-15
createProtocol()
returns an anonymous class instance that implements the
Runnable
interface. The
run()
method of this instance simply calls the static method
CompressPro−
tocolFactory.handleClient()
, which implements the server-side compression protocol.
Note that we do
not
need a separate
CompressProtocol
class, because
createProtocol()
returns the type of instance (one that implements
Runnable
) that we need.
2.
handleClient()
: lines 17-38
Given a socket connected to the compression client, read the uncompressed bytes from
the client and write the compressed bytes back.
Get socket I/O streams:
lines 26-27
The socket's output stream is wrapped in a
GZIPOutputStream
. The sequence of bytes
written to this stream is compressed, using the GZIP algorithm, before being written
to the underlying output stream.
Read uncompressed and write compressed bytes:
lines 29-33
The while loop reads from the socket input stream and writes to the
GZIPOutputStream
,
which in turn writes to the socket output stream, until the end-of-stream indication is
received.
Flush and close:
lines 35-44
Calling
finish()
on the
GZIPOutputStream
is necessary to flush any bytes that may be
buffered by the compression algorithm.
A simple iterative version of the server can be found in
CompressServer.java
on the topic's
Web site.
Search WWH ::
Custom Search