package PortForwarder;
import java.net.*;

// Written by Sean R. Owens, sean at guild dot net, released to the
// public domain.  Share and enjoy.  Since some people argue that it is
// impossible to release software to the public domain, you are also free
// to use this code under any version of the GPL, LPGL, or BSD licenses,
// or contact me for use of another license.
// http://darksleep.com/player
public class Server {
    
    int listenPort = 0;
    String destName = null;
    int destPort= 0;
    int connectionCount = 1;

    ServerSocket serverSocket = null;

    public Server(int listenPort, String destName, int destPort) {
	this.listenPort = listenPort;
	this.destName = destName;
	this.destPort = destPort;
	try {
	    serverSocket = new ServerSocket(listenPort);
	}
	catch(Exception e) {
	    System.err.println("Exception creating serverSocket:"+e);
	    e.printStackTrace();
	}
    }

    public void go() {
	while(true) {
	    try {
		Socket inConnection = serverSocket.accept() ;
		System.err.println("New connection established with "+ inConnection);
		
		Socket outConnection = new Socket(destName, destPort);
		
		Handler inHandler = new Handler(":incoming"+connectionCount+":",inConnection, outConnection);
		Handler outHandler = new Handler(":outgoing"+connectionCount+":",outConnection, inConnection);
		connectionCount++;
	    }
	    catch(Exception e) {
		System.err.println("Exception in go:"+e);
		e.printStackTrace();
	    }
	    
	}

    }

    public static void main(String argv[]) {
	int listenPort = 0;
	int destPort = 0;
	if(argv.length != 3) {
	    System.err.println("usage: Server listenPort destName destPort");
	    System.exit(1);
	}
	listenPort = Integer.parseInt(argv[0]);
	destPort = Integer.parseInt(argv[2]);
	Server server = new Server(listenPort, argv[1], destPort);
	server.go();
    }    
}

