The Daytime Service

daytime is an ancient (by Internet standards) network service that simply sends the current local day and time as an ASCII string to any client that connects to port 13, via either TCP or UDP. Example 6-10 is a simple daytime server that accepts TCP connections using a ServerSocketChannel and sends responses to the client with a SocketChannel. This simple program is followed by Example 6-11, a more robust implementation that handles TCP and UDP connections, and includes exception handling and error logging. This more advanced server demonstrates ServerSocketChannel and DatagramChannel , and shows how a program can wait for activity on both channels simultaneously using a Selector object. This section concludes with Example 6-12, a simple datagram-based client of the daytime service, suitable for testing Example 6-11.

SimpleDaytimeServer is, as its name implies, a simple program. It first creates a ServerSocketChannel , and then binds it to port 13 or some other port specified on the command line. Binding the channel to a port is done by querying the underlying java.net.ServerSocket object and using its bind( ) method. It obtains a CharsetEncoder object that it will use later to encode the characters of the daytime string into ASCII bytes.

Next, the server enters an infinite loop to service clients. This loop is made particularly simple by the fact that there is no need to read or parse client requests: the server sends a date and time string to every client that ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.