Server Example
Home ] Up ] The ServerSocket Class ] Server Example ] Using a telnet Client ] [ Server Example ] Multi-Threaded Example ]

 

 

Here's a simple Java client written to access ReverseServer:

package networking;

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

import java.net.Socket;
import java.net.UnknownHostException;

/**
 *   Application to connect to a specified host and port
 *   and print the output text received from that connection.
 */
public class ReverseClient
{
  /**
   * 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 ReverseClient <host> <socket>");
    }
    else
    {
      String host = null;
      int    port = -1;
      host = args[0];
      // Convert port string to integer
      try
      {
        port = Integer.parseInt(args[1]);
      }
      catch (NumberFormatException e)
      {
        System.err.println("Invalid port : [" + port +"]");
        return;
      }
      
      // Connect a BufferedReader to System.in
      BufferedReader inputReader = new BufferedReader(
          new InputStreamReader(System.in) );
      
      Socket socket;
      try
      {
        socket = new Socket(host, port);
        
        // Connect a BufferedReader to read from the socket
        BufferedReader socketReader = new BufferedReader(
            new InputStreamReader( socket.getInputStream() ) );
        
        // Connect a PrintWriter to write to the socket
        PrintWriter socketWriter = new PrintWriter(
            new OutputStreamWriter(socket.getOutputStream() ),
            true // autoflush
            );
        
        while (true)
        {
          // Read the reverse server's response
          String line = socketReader.readLine();
          if (line == null)
            break;  // We hit the end
          System.out.println(line);
          line = inputReader.readLine();
          if (line == null)
            line = "";  // Send an empty line for end of input
          socketWriter.println(line);
        }
      }
      catch (UnknownHostException ex)
      {
        ex.printStackTrace();
        return;
      }
      catch (IOException ex)
      {
        ex.printStackTrace();
        return;
      }
    }
  }
}
 
The page was last updated February 19, 2008