//: RelayOneWay.java

/** Very simple server that just relays whatever the client sends onto
  * another server and then sends the server response back to the 
  * original client.
  * @author Mark Crocker
  * @author http://www.markcrocker.com/~mcrocker/
  * @version 0.91 (Beta) 2000-May-13
  * Derived from @see c15.MultiJabberServer from 'Thinking in Java,
  * 2nd ed.' by Bruce Eckel www.BruceEckel.com.  
  */

/* This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.  
 */

import java.io.*;
import java.net.*;

/** RelayOneWay is the main workhorse class of RelayD and
  * AuthNewsGateWay. It listens on one port and sends what it "hears"
  * to the other port.  Two instances are needed for complete two-way
  * communications.
  * @param Socket to listen to and Socket to send to
  * @return No return value
  * @exception IOException or InterruptedException thrown */
class RelayOneWay extends Thread {  

    /** A socket to listen to */
    private Socket socketIn;
    /** A socket to send to */
    private Socket socketOut;
    private InputStreamReader in;
    private OutputStreamWriter out;
    /** Constructor just need a socket to listen to and one to send to 
      * @param Socket to listen to and Socket to send to
      * @return No return value
      * @exception IOException or InterruptedException
      */
    public RelayOneWay(Socket sIn, Socket sOut ) 
	throws IOException, InterruptedException {

	socketIn = sIn;
	socketOut = sOut;

	// Server input socket
	System.out.println("Connection accepted: "+ socketIn);
	in = new InputStreamReader(socketIn.getInputStream());
	
	// Server output is automatically flushed
	// by PrintWriter:
	out =  new OutputStreamWriter(socketOut.getOutputStream());
	start(); //Calls run()
    }

    /** Run method so that this can be a threaded class, which allows
      * multiple connections.
      * @param No parameters
      * @return No return value
      * @exception IOException
      */
    public void run() {
	char buf[] = new char[8192];
	int data = 0;
	try {
	    // Listen to client and relay to other server
	    while( (data = in.read(buf, 0, 8192)) != -1) {
		out.write(buf, 0, data);
		out.flush();
	    }
	} catch (IOException e) {
		
	    // Always close the two sockets...
	} finally {
	    try {
		System.out.println("close sockets...");
		socketIn.close();
		socketOut.close();
	    } catch (IOException e) {}
	}
    }
} ///:~


/* Todo:
 * 1. Logging.
 * 2. Debug Mode.
 * 3. Quiet Mode.
 * 4. Buffer size as a parameter, not hard wired.
 * 5. Improved documentation.
 */