package testRMI;

import java.io.IOException;
import java.net.ServerSocket;
import java.rmi.Remote;
import java.rmi.server.RemoteObject;

public class ExportChannel {

	private static int portCounter = 20000;

	private int port = 0;

	private ServerSocket serverSocket = null;

	private Remote stub = null;

	public ExportChannel(Remote remote) {
		try {
			this.stub = RemoteObject.toStub(remote);
			this.port = portCounter++;
			this.serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public int getPort() {
		return port;
	}

	public void export() {
		Executor ex = new Executor();
		new Thread(ex).start();
	}

	class Executor implements Runnable {
		public void run() {
			try {
				while (true) {
					new ServerThread(serverSocket.accept(), stub).start();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
