The Java Program: Connection.java

  1 // Connection.java -- thread for all communication with a client
  2 
  3 import java.net.Socket;
  4 import java.io.IOException;
  5 import java.io.InputStreamReader;
  6 import java.io.BufferedReader;
  7 import java.io.PrintWriter;
  8 
  9 class Connection extends Thread {
 10    private final Socket client;
 11    private BufferedReader in = null;
 12    private PrintWriter out = null;
 13 
 14    // Initialize the streams and start the thread
 15    public Connection (Socket client_socket) {
 16       client = client_socket;
 17       System.out.println ("Server: connection from "+client.getInetAddress());
 18       try { 
 19          in = new BufferedReader (new InputStreamReader (client.getInputStream()));
 20          out = new PrintWriter (client.getOutputStream());
 21          this.start();
 22       } catch (IOException e) {
 23          close ();
 24       }
 25    }
 26     
 27    private void close () {
 28       try {
 29          client.close();
 30       } catch (IOException e) {
 31          e.printStackTrace (System.err);
 32       }
 33    } 
 34 
 35    // Read a line, reverse it, send it back.  
 36    public void run() {
 37       try {
 38          while (true) {
 39             // read in a line
 40             final String line = in.readLine();
 41             if (line == null) break;
 42             System.out.println ("Server: got line:  "+ line);
 43 
 44             // reverse it
 45             final int len = line.length();
 46             final StringBuffer revline = new StringBuffer(len);
 47             for(int i = len-1; i >= 0; i--) 
 48                revline.insert(len-1-i, line.charAt(i));
 49 
 50             // and write out the reversed line
 51             out.println(revline);
 52             out.flush();
 53          }
 54       } catch (IOException e) {
 55          e.printStackTrace (System.err);
 56       } finally {
 57          close ();
 58       }
 59       System.out.println ("Server: connection closed from " +
 60                           client.getInetAddress());
 61    }
 62 }