Using channels with a time server
The time server and client that were introduced in Chapter 1, Getting Started with Network Programming, will be implemented here to demonstrate the use of buffers and channels. These applications are simple, but they illustrate how buffers and channels can be used together. We will start by creating a server and then create a client that uses the server.
Creating a time server
The following code is the initial declaration of the ServerSocketChannelTimeServer
class, which will be our time server. The ServerSocketChannel
class's open
method creates a ServerSocketChannel
instance. The socket
method retrieves the ServerSocket
instance for the channel. The bind
method then associates this server socket with port 5000
. While the ServerSocketChannel
class has a close
method, it is easier to use the try-with-resources block:
public class ServerSocketChannelTimeServer { public static void main(String[] args) { System.out.println("Time Server started...