Minimal Client

In this example, the client connects to the server and the server returns a "canned" message and breaks the connection. Thus, the client and server programs function at the "Hello, World!" level.

The important functionality of this client is located in the runClient method. A minimal user interface is created in the constructor, and the program is driven from the main method.

Notice the nearly identical structure of the minimal server and client programs.

import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;

public class Client_Basic extends Frame  {

//*****  Basic, single-thread client
//            expects to find server on gamma.cs.unc.edu:8888

TextArea logDisplay;
public static final string DEFAULT_HOST = "gamma.cs.unc.edu";
public static final int DEFAULT_PORT = 8888;

  public Client_Basic ()  {

    super ( "Client_Basic " );
    logDisplay = new TextArea ( 40, 10 );
    add ( "Center", logDisplay );
    resize ( 400, 300 );
    show ();

  }  // end Client_Basic constructor

// **************

  public void runClient ( )  {

  Socket connection;
  InputStream input;
  char c;

    try  {
      connection = new Socket ( InetAddress.getByName (DEFAULT_HOST ), DEFAULT_PORT );
      logDisplay.setText ( "Socket created:  connecting to server\n" );
      input = connection.getInputStream ();
      logDisplay.appendText ( "InputStream created\n" );
      logDisplay.appendText ( "Text received from server = \n     " );
      while ( (c = (char) input.read () ) != '\n' ) 
         logDisplay.appendText ( String.valueOf ( c ) ); 
      logDisplay.appendText ( "\n" );
      connection.close ();
      logDisplay.appendText ( "Connection closed\n" );
    }  // end try

    catch ( IOException except)  {
      except.printStackTrace ();
    }  // end catch

  }  // end runClient 

// **************

  public boolean handleEvent ( Event event )  {

    if ( event.id == Event.WINDOW_ICONIFY )  {
      hide ();
      dispose ();
      System.exit ( 0 );
    }  // end if

    return super.handleEvent ( event );

  }  // end handleEvent 

// **************

  public static void main ( String [ ] args )  {

    Client_Basic client = new Client_Basic ();
    client.runClient ();

  }  // end main

}  // end Client_Basic