package com.icontrols.bridge.wallpad;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icontrols.bridge.common.SERVER_INFO;


public class IMapMultiSocket{
	private static final Logger logger = LoggerFactory.getLogger(IMapMultiSocket.class);

	public IMapMultiSocket() {
		logger.info("*************************************************************************");
		logger.info("* Socket 다중 접속 서버 실행 .. ");
		logger.info("* 서버 소켓 포트 : " + SERVER_INFO.WalladReceivePort);
		logger.info("*************************************************************************");
		
		ServerSocket server = null;
		long connectCount = 0;
		try {
			server = new ServerSocket(SERVER_INFO.WalladReceivePort);
			
			while(true) {
				logger.info("[클라이언트의 접속을 기다리고 있습니다......]");
				
				Socket clientSocket = server.accept();
				connectCount++;
				
				InetAddress ia = clientSocket.getInetAddress();
				int port = clientSocket.getLocalPort();
				
				String ip = ia.getHostAddress();
				
				logger.info("* --> connectCount = [" + connectCount + "] -- 접속 포트 = [" + port + "] -- CLIENT IP = ["+ip+"]");
				
				if (connectCount > 2000000000) connectCount = 0;
				
				new MsgServerHandler(clientSocket).start();
			}
		}catch(Exception e) { 
			logger.error("[IMapMultiSocket] - 메인 에러....    " + e.getMessage());
			logger.error(e.getStackTrace().toString());
			
		} finally {
			try {
				server.close();
			}catch(Exception e) {
				logger.error("무시.");
			}
			
			logger.info("**************************** 서버 재실행 **********************************");
			new IMapMultiSocket();
		}
		
	}
}
