FileDocCategorySizeDatePackage
RelayServer.javaAPI DocExample2428Wed Mar 29 15:30:00 BST 2000tuning.distrib

RelayServer

public class RelayServer extends Object implements Runnable

Fields Summary
Socket
in_s
Socket
out_s
String
message
Constructors Summary
public RelayServer(Socket in, Socket out, String msg)

    in_s = in;
    out_s = out;
    message = msg;
  
Methods Summary
public static voidmain(java.lang.String[] args)

    ServerSocket srvr = null;
    try
    {
      //Start a server socket on the localhost at the given port 
      srvr = new ServerSocket(Integer.parseInt(args[1]));
      for(;;)
      {
        //Block until a connection is made to us.
        Socket sclient = srvr.accept();
        System.out.println("Trying to connect to " + args[0]);
        //Connect to the 'real' server
        Socket ssrvr = new Socket(args[0], Integer.parseInt(args[1]));
        System.out.println("Connected to " + args[0]);
        //Start two threads, one to relay client to server communications,
        //and one to relay server to client communications.
        (new Thread(new RelayServer(sclient, ssrvr, "CLIENT->SERVER"))).start();
        (new Thread(new RelayServer(ssrvr, sclient, "SERVER->CLIENT"))).start();
      }
    }
    catch (Exception e)
    {
      System.out.println("SERVER TERMINATED: " + e.getMessage());
      try{srvr.close();}catch(Exception e2){}
    }
  
public voidrun()

    try
    {
      InputStream in = in_s.getInputStream();
      OutputStream out = out_s.getOutputStream();
      byte[] buf = new byte[8192];
      int len;
      for(;;)
      {
        len = in.read(buf);
        System.out.print(message);
        System.out.println(new String(buf, 0, len));
        out.write(buf, 0, len);
      }
    }
    catch (Exception e)
    {
      System.out.print(message);
      System.out.println(" TERMINATED");
      System.out.flush();
      try{in_s.close();}catch(Exception e2){}
      try{out_s.close();}catch(Exception e2){}
    }