[ Team LiB ] Previous Section Next Section

5.4 A Simple Network Client

Example 5-4 is a simple network client program that does not use the URL class. Instead, it uses java.net.Socket to connect to server. It sends a line of text to the server, and then reads and prints out the server's response. The main point of interest in this example is the introduction of the Socket class, which creates a stream-based network connection between a client and a server. To create a network connection to another host, you simply create a Socket, specifying the desired host and port. If there is a program (a server) running on the specified host and listening for connections on the specified port, the Socket( ) constructor returns a Socket object you can use to communicate with the server. (If there is not a server listening on the specified host and port, or if anything goes wrong—and many things can go wrong with networking—the Socket( ) constructor throws an exception.)

If you are not familiar with hosts and ports, think of the host as a post office and the port as a post-office box. Just as a post office has many different post-office boxes, any host on the network can run many different servers at a time. Different servers use different ports for their addresses. To establish a connection, you must specify both the correct host and the correct port. Many services have standard default ports. Web servers run on port 80, POP email servers run on port 110, and so on.

Once you have a Socket object, you are connected, across the network, to a server. The getInputStream( ) method of the socket returns an InputStream you can use to read bytes from the server, and getOutputStream( ) returns an OutputStream you can use to write bytes to the server. This is exactly what this Connect program does.

Despite its simplicity, our simple Connect client is actually useful in conjunction with simple network servers like "daytime" (port 13) and "finger" (port 79). For example, here is how you can use the program to find out the current time (daytime) and to find out who is logged on to a server (finger):

java je3.net.Connect time-a.nist.gov 13
java je3.net.Connect rtfm.mit.edu 79
Example 5-4. Connect.java
package je3.net;
import java.io.*;
import java.net.*;

/**
 * A simple network client that establishes a network connection to a specified
 * port on a specified host, sends an optional message across the connection,
 * reads the response from the server, and exits.  A suitable client for simple
 * network services like the daytime or finger.
 **/
public class Connect {
    public static void main(String[  ] args) {
        try {  // Handle exceptions below
            // Get our command-line arguments
            String hostname = args[0];
            int port = Integer.parseInt(args[1]);
            String message = "";
            if (args.length > 2) 
                for(int i = 2; i < args.length; i++) message += args[i] + " ";
            
            // Create a Socket connected to the specified host and port.
            Socket s = new Socket(hostname, port);

            // Get the socket output stream and wrap a PrintWriter around it
            PrintWriter out = new PrintWriter(s.getOutputStream( ));

            // Send the specified message through the socket to the server.
            out.print(message + "\r\n");
            out.flush( );  // Send it now.
            
            // Get an input stream from the socket and wrap a BufferedReader
            // around it, so we can read lines of text from the server.
            BufferedReader in =
                new BufferedReader(new InputStreamReader(s.getInputStream( )));

            // Before we start reading the server's response, tell the socket
            // that we don't want to wait more than 3 seconds
            s.setSoTimeout(3000);

            // Now read lines from the server until the server closes the
            // connection (and we get a null return indicating EOF) or until
            // the server is silent for 3 seconds.
            try {
                String line;                          
                while((line = in.readLine( )) != null) // If we get a line
                    System.out.println(line);         // print it out.
            }
            catch(SocketTimeoutException e) {
                // We end up here if readLine( ) times out.
                System.err.println("Timeout; no response from server.");
            }
            
            out.close( );  // Close the output stream
            in.close( );   // Close the input stream
            s.close( );    // Close the socket
        }
        catch(IOException e) {  // Handle IO and network exceptions here
            System.err.println(e);
        }
        catch(NumberFormatException e) {  // Bad port number
            System.err.println("You must specify the port as a number");
        }
        catch(ArrayIndexOutOfBoundsException e) {  // wrong # of args
            System.err.println("Usage: Connect <hostname> <port> message...");
        }
    }
}
    [ Team LiB ] Previous Section Next Section