Java Reference
In-Depth Information
Note that the connection is returned a java.net.Socket object, the same as you used
for clients in the previous chapter. The daytime protocol requires the server (and only
the server) to talk, so get an OutputStream from the socket. Because the daytime protocol
requires text, chain this to an OutputStreamWriter :
OutputStream out = connection . getOutputStream ();
Writer writer = new OutputStreamWriter ( writer , "ASCII" );
Now get the current time and write it onto the stream. The daytime protocol doesn't
require any particular format other than that it be human readable, so let Java pick for
you:
Date now = new Date ();
out . write ( now . toString () + "\r\n" );
Do note, however, the use of a carriage return/linefeed pair to terminate the line. This
is almost always what you want in a network server. You should explicitly choose this
rather than using the system line separator, whether explicitly with System.getProper
ty("line.separator") or implicitly via a method such as println() .
Finally, flush the connection and close it:
out . flush ();
connection . close ();
You won't always have to close the connection after just one write. Many protocols, dict
and HTTP 1.1 for instance, allow clients to send multiple requests over a single socket
and expect the server to send multiple responses. Some protocols such as FTP can even
hold a socket open indefinitely. However, the daytime protocol only allows a single
response.
If the client closes the connection while the server is still operating, the input and/or
output streams that connect the server to the client throw an InterruptedIOExcep
tion on the next read or write. In either case, the server should then get ready to process
the next incoming connection.
Of course, you'll want to do all this repeatedly, so you'll put this all inside a loop. Each
pass through the loop invokes the accept() method once. This returns a Socket object
representing the connection between the remote client and the local server. Interaction
with the client takes place through this Socket object. For example:
ServerSocket server = new ServerSocket ( port );
while ( true ) {
try ( Socket connection = server . accept ()) {
Writer out = new OutputStreamWriter ( connection . getOutputStream ());
Date now = new Date ();
out . write ( now . toString () + "\r\n" );
out . flush ();
} catch ( IOException ex ) {
// problem with one client; don't shut down the server
Search WWH ::




Custom Search