package net.bakingpowder.jspl.tcprelay.distributed.recieveRelay;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;



/**
 * @author Tomoo D. Mizukami/JAIST/Softbank Publishing Inc.
 *
 * !)!)RecieveTCPRelay!)!)!)!)!)!)!)!)!)TCPRelay!)!)!)!)!)!)!)!)!)!)
 * !)!)!)!)!)!)!)!)!)!)!)!)!)TCPRelay!)!)!)!)!)!)!)!)!)!)!)!)!)!)
 */
public class RecieveTCPRelay implements Runnable {
	private ServerSocket mainSocket = null;
	private int portNumber;
	private boolean stopper = false;
	
	/**
	 * @param portNumber !)!)!)!)!)!)!)!)!)
	 * @throws Exception!)!)!)!)!)
	 */
	public RecieveTCPRelay(int portNumber)
			throws Exception {
		this.portNumber = portNumber;

		mainSocket = new ServerSocket(portNumber);
	}
	
	/**
	 * @param stopper The stopper to set.
	 */
	public synchronized void setStopper(boolean stopper) {
		if (cc!=null){
			cc.stopd();
		}
		this.stopper = stopper;
		
		try {
			mainSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		
	private RecieveConnectControl cc;
	
	private void startCC(){
		try {
			Socket newSocket;
				newSocket = mainSocket.accept();
				System.out.println("!!!!!! RECIEVEPROXY !!!! :Socket has been accepted");
			cc = new RecieveConnectControl(newSocket);
		
		} catch (IOException e) {
			System.out.println("IOException");

		}		
	}
	
	public void run() {

		while (!stopper) {
			this.startCC();
		}
		
		try {
			mainSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}