Minimal Server

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 server is located in the runServer method. A minimal user interface is created in the constructor, and the program is driven from the main method.

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

public class Server_Basic extends Frame  {

//*****  Basic, single-thread server
//            expected to be run 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 Server_Basic ()  {

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

  }  // end Server_Basic constructor

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

  public void runServer ( )  {

  ServerSocket listenSocket;
  Socket connection;
  OutputStream output;

    try  {
      listenSocket = new ServerSocket ( DEFAULT_PORT);
      logDisplay.setText ( "Server started:  listening on port " + DEFAULT_PORT + "\n" );
      connection =  listenSocket.accept ();
      logDisplay.appendText ( "Connection request received\n" );
      output = connection.getOutputStream ();
      String string = new String ( "Connection was successful\n" );
      logDisplay.appendText ( "Text sent to client = \n     " );
      for ( int i = 0; i < string.length(); i++ ) 
        output.write ( (int) string.charAt ( i ) );
      logDisplay.appendText ( string );
      logDisplay.appendText ( "Connection complete; closing socket\n" );
      connection.close ();
    }  // end try

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

  }  // end runServer 

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

  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 )  {

    Server_Basic server = new Server_Basic ();
    server.runServer ();

  }  // end main

}  // end Server_Basic