package opc.ua.communication;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TcpServerSocket {

	// server socket
	private ServerSocket srvSocket;
	// default server port number
	private static int defaultServerPort = 10101; 
	// logger
	private Logger logger;
	// run the server
	private boolean run;
	
	/** 
	 * constructor
	 */
	public TcpServerSocket() {
		this(defaultServerPort);
	}
	
	/**
	 * constructor
	 * @param port
	 */
	public TcpServerSocket(int port) {
		// create logger
		logger = Logger.getLogger(this.getClass().getSimpleName());
		logger.addHandler((Handler)(new TcpLoggerHandler()));
		logger.setLevel(Level.ALL);
		logger.fine("starting server");
		try {	
			// create socket
			srvSocket = new ServerSocket(port);
			logger.fine("server started on port " + port);
			
			// try to listen
			this.run = true;
			while (run) {
				// accept
				Socket socket = srvSocket.accept();
				logger.fine("new client asked for connection");
				
				// start new tcp listening thread for each client
				logger.fine("starting new thread to client");
				new Thread(new TcpThread(socket)).start();
			}
			srvSocket.close();
			logger.fine("server stopping");
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	/**
	 * stops the server
	 */
	public void stop() {
		this.run = false;
	}
	
}
