//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.
//Minor changes by David Matuszek, October 14, 2004



import java.net.*;
import java.io.*;

/** Listens on port 5678.  When a client connects, the server
 * reverses whatever the client sends, and sends it back.
 */
public class ReverseServer {
    public static void main(String[] args) {
        String s; // the string to reverse
        int size; // the length of the string
        char[] c; // the reversed characters
        
        System.out.println("The server has started.");
        try {
            ServerSocket server = new ServerSocket(5678);
            Socket client = server.accept(); // <=== blocking call
            System.out.println("Reverse Server Connected on port 5678");
            BufferedReader input =
                new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter output = new PrintWriter(client.getOutputStream(), true);
            while ((s = input.readLine()) != null) {
                size = s.length();
                c = new char[size];
                for (int i = 0; i < size; i++)
                    c[i] = s.charAt(size - 1 - i);
                output.println(c);
                output.flush();
            }
            input.close();
            output.close();
            client.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            System.out.println("The server has stopped.");

        }
    }
}