| All About Sockets

## Reading from and Writing to a Socket

> The following program is a simple example of how to establish a connection from a client program to a server program through the use of sockets. The Socket class in the java.net package is a platform-independent implementation of the client end of a two-way communication link between a client and a server. The Socket class sits on top of a platform-dependent implementation, hiding the details of any particular system from your Java program. By using the java.net Socket class instead of relying on native code, your Java programs can communicate over the network in a platform-independent fashion.

> This client program, EchoTest, connects to the standard Echo server (on port 7) via a socket. The client both reads from and writes to the socket. EchoTest sends all text typed into its standard input to the Echo server by writing the text to the socket. The server echos all input it receives from the client back through the socket to the client. The client program reads and displays the data passed back to it from the server:

> >     import java.io.*;
> >     import java.net.*;

> >     public class EchoTest {
> >         public static void main(String[] args) {
> >             Socket echoSocket = null;
> >             DataOutputStream os = null;
> >             DataInputStream is = null;
> >     	DataInputStream stdIn = new DataInputStream(System.in);

> >             try {
> >                 echoSocket = new Socket("taranis", 7);
> >                 os = new DataOutputStream(echoSocket.getOutputStream());
> >                 is = new DataInputStream(echoSocket.getInputStream());
> >             } catch (UnknownHostException e) {
> >                 System.err.println("Don't know about host: taranis");
> >             } catch (IOException e) {
> >                 System.err.println("Couldn't get I/O for the connection to: taranis");
> >             }

> >             if (echoSocket != null && os != null && is != null) {
> >                 try {
> >                     String userInput;

> >                     while ((userInput = stdIn.readLine()) != null) {
> >                         os.writeBytes(userInput);
> >                         os.writeByte('\n');
> >                         System.out.println("echo: " + is.readLine());
> >                     }
> >                     os.close();
> >                     is.close();
> >                     echoSocket.close();
> >                 } catch (IOException e) {
> >                     System.err.println("I/O failed on the connection to: taranis");
> >                 }
> >             }
> >         }
> >     }

> Let's walk through the program and investigate the interesting bits.

> The following three lines of code within the first `try` block of the `main()` method are critical--they establish the socket connection between the client and the server and open an input stream and an output stream on the socket:

> >     echoSocket = new Socket("taranis", 7);
> >     os = new DataOutputStream(echoSocket.getOutputStream());
> >     is = new DataInputStream(echoSocket.getInputStream());

> The first line in this sequence creates a new Socket object and names it `echoSocket`. The Socket constructor used here (there are three others) requires the name of the machine and the port number that you want to connect to. The example program uses the hostname `taranis`, which is the name of a (hypothetical) machine on our local network. When you type in and run this program on your machine, you should change this to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine that you want to connect to. The second argument is the port number. Port number 7 is the port that the Echo server listens to.

> The second line in the code snippet above opens an output stream on the socket, and the third line opens an input stream on the socket. EchoTest merely needs to write to the output stream and read from the input stream to communicate through the socket to the server. The rest of the program achieves this. If you are not yet familiar with input and output streams, you may wish to read Input and Output Streams.

> The next section of code reads from EchoTest's standard input stream (where the user can type data) a line at a time. EchoTest immediately writes the input text followed by a newline character to the output stream connected to the socket.

> >     String userInput;

> >     while ((userInput = stdIn.readLine()) != null) {
> >         os.writeBytes(userInput);
> >         os.writeByte('\n');
> >         System.out.println("echo: " + is.readLine());
> >     }

> The last line in the `while` loop reads a line of information from the input stream connected to the socket. The `readLine()` method blocks until the server echos the information back to EchoTest. When `readline()` returns, EchoTest prints the information to the standard output.

> This loop continues--EchoTest reads input from the user, sends it to the Echo server, gets a response from the server and displays it--until the user types an end-of-input character.

> When the user types an end-of-input character, the `while` loop terminates and the program continues, executing the next three lines of code:

> >     os.close();
> >     is.close();
> >     echoSocket.close();

> These lines of code fall into the category of housekeeping. A well-behaved program always cleans up after itself, and this program is well-behaved. These three lines of code close the input and output streams connected to the socket, and close the socket connection to the server. The order here is important--you should close any streams connected to a socket before you close the socket itself.

> This client program is straightforward and simple because the Echo server implements a simple protocol. The client sends text to the server, the server echos it back. When your client programs are talking to a more complicated server such as an http server, your client program will also be more complicated. However, the basics are much the same as they are in this program:

> 1. Open a socket.
> 2. Open an input stream and output stream to the socket.
> 3. Read from and write to the stream according to the server's protocol.
> 4. Close streams.
> 5. Close sockets.
> Only step 3 differs from client to client, depending on the server. The other steps remain largely the same.

#### See also

> java.net.Socket

| All About Sockets