サーバ側Socketによるマルチスレッド通信

1424 ワード

public class MultiThreadServer {
	private static int port = new GetConfigurationInfo().port;
	private ServerSocket serverSocket;
	private ExecutorService executorService; // 
	private final int POOL_SIZE = 10; // CPU 
	
	public MultiThreadServer(){
		try {
			serverSocket = new ServerSocket(port);
			//Runtime availableProcessor() CPU 
			executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
			System.out.println(" ");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void service(){
		while(true){
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				executorService.execute(new Handler(socket));// 
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	
	public static void main(String[] args) {
		MultiThreadServer multi = new MultiThreadServer();
		multi.service();
		
	}
	
}

class Handler implements Runnable{
	private Socket socket;
	public Handler(Socket socket){
		this.socket = socket;
	}
		
	public void run(){
		// 	
		
	}
}