Socket

The class Socket is used to create a stream-based network connection between a client and a server. To establish the connection, create a Socket object by specifying the desired host and port. If there is a server running on that host, and, it is listening for connections on the specified port, then the constructor will return a Socket object that can be used to communicate with the server. If one of any number of things is not right, the constructor will throw an exception.

In the example, time-A.timefreq.bldrdoc.gov is a Unix box operated by the NIST in Boulder, Colorado, that hosts a Cesium atomic clock. Port 13 is the standard port for Unix's "time of day" server. When the host computer receives a connection request on port 13: a network connection is established with the "time of day" server (a "socket" is created), the server sends back one line of data, and the connection is closed.

Note the use of a try/catch block. Since there are many things that can go wrong with a network connection, most of the network-related methods throw derivations of the I/O exception base class.

Once the Socket object is created (the network connection is established), the getInputStream() method returns an InputStream object that can be "wrapped" and used like any standard I/O object. The BufferedReader class offers a readLine() method that can read an entire line of text in one call.

When the "time of day" server has finished its output, it closes the network connection. This causes the Socket object to return an "end of file", which passes through the InputStreamReader object, which causes the BufferedReader object to return a null String.

A chain reaction of "shutting down" the Java I/O objects is initiated by telling the outermost wrapper object to close() itself.