Example 1
Home ] Up ] The Socket Class ] [ Example 1 ] Example 2 ]

 

 

Here's a client program that reads from a specified socket on a specified host, and assumes that the results are simple text:

package networking;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.net.Socket;

/**
 *   Application to connect to a specified host and port
 *   and print the output text received from that connection.
 */
public class SocketTest
{
  /**
   * Main entry point
   * @param args the command line arguments:
   *             args[0] : host name
   *             args[1] : port number
   */
  public static void main(String[] args)
  {
    if (args.length < 2)
    {
      System.err.println("Usage: java SocketTest <host> <socket>");
    }
    else
    {
      String host = null;
      int    port = -1;
      try
      {
        host = args[0];
        // Convert port string to integer
        port = Integer.parseInt(args[1]);
        
        // Open the socket
        Socket socket = new Socket(host, port);
        // Read from the socket
        BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(
                                        socket.getInputStream()
                                    )
                                );
        // Read line by line until the end
        while (true)
        {
          String line = reader.readLine();
          if (line == null)
            break;  // We hit the end
          System.out.println(line);
        }
      }
      catch (NumberFormatException e)
      {
        System.err.println("Invalid port : [" + port +"]");
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
  }
}

If you supply the following arguments to this program:

time-A.timefreq.bldrdoc.gov 13

(which is the time of day service running on a machine operated by the National Institute of Standards and Technology (NIST) in Boulder, Colorado) it will output the following:

54140 07-02-09 18:01:53 00 0 0  11.6 UTC(NIST) *

(or something similar).

 

The page was last updated February 19, 2008