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

 

 

Here's a simple ReverseServer, implemented using ServerSocket.

It simply accepts strings sent to it by its client, and returns the string with all the characters reversed.

package networking;

import java.net.ServerSocket;
import java.net.Socket;

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

/**
 *   Application to act as a 'Reverse' server.
 *   An application can connect to this server on the specified port
 *   and send it text.  The server will reverse the text and send it back.
 *
 *   @author Bryan J. Higgs, 10 October 1999
 */
public class ReverseServer
{
  /**
   *   Main entry point.
   *   @param args the command line arguments
   *               args[0] contains port to use
   */
  public static void main(String[] args)
  {
    int port = -1;
    try
    {
      port = Integer.parseInt(args[0]);
    }
    catch (NumberFormatException e)
    {
      System.err.println("Invalid port number: " + args[0]);
      return;
    }
    
    ServerSocket socket = null;
    Socket incoming = null;
    BufferedReader in = null;
    PrintWriter out = null;
    try
    {
      socket = new ServerSocket(port);
      // Wait on server socket for connection requests
      incoming = socket.accept();
      // Connection requested; get the input stream
      in = new BufferedReader(
                new InputStreamReader(
                    incoming.getInputStream()));
      // Get the output stream
      out = new PrintWriter(incoming.getOutputStream(),
                            true        // autoflush
                           );
      
      // Output greeting
      out.println(
          "Welcome to the Reverse Server!" +
          " Enter an empty line to exit.");
      
      // Loop, reversing each line received.
      while (true)
      {
        String line = in.readLine();
        if (line == null || line.equals(""))
          break; // We are at the end
        // We read a line, so reverse it
        StringBuffer buffer = new StringBuffer(line);
        line = buffer.reverse().toString();
        // and return the result
        out.println(line);
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      // Close everything necessary
      try
      {
        if (out != null)
          out.close();
        if (in != null)
          in.close();
        if (incoming != null)
          incoming.close();
        if (socket != null)
          socket.close();
      }
      catch (IOException e)
      {
        // Ignore any errors here
      }
    }
  }
}
 
The page was last updated February 19, 2008