All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.tom.transport.aio.AioServer Maven / Gradle / Ivy

The newest version!
package cn.tom.transport.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;

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

import cn.tom.kit.ThreadPool;
import cn.tom.kit.ThreadPool.DefaultThreadFactory;
import cn.tom.transport.IoAdaptor;
import cn.tom.transport.Server;

public class AioServer implements Server {
	private static final Logger log = LoggerFactory.getLogger(AioServer.class);
	protected String host = "0.0.0.0";
	protected int port;
	protected String serverAddr;
	protected String serverName = "AioServer";
	protected AsynchronousServerSocketChannel serverChannel;
	private AcceptHandler acceptHandler;
	
	public AioServer(int port) {
		this.port = port;
	}

	public AioServer(String host, int port) {
		this.host = host;
		this.port = port;
	}

	@Override
	public void start() throws IOException {
		AsynchronousChannelGroup asynchronousChannelGroup = AsynchronousChannelGroup.withFixedThreadPool(ThreadPool.cpuCoreCount,  new DefaultThreadFactory("AioServer-pool-"));
		serverChannel = AsynchronousServerSocketChannel.open(asynchronousChannelGroup);
		serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
		serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 1 * 1024 * 1024); //1M 缓存区
		InetSocketAddress socketAddress = new InetSocketAddress(host, port);
		serverChannel.bind(socketAddress, 1000);
		accept(acceptHandler);
	}
	
	public void sync(){
		while(serverChannel.isOpen()){
			log.info("{} serving@{}:{}", this.serverName, this.host, this.port);
			try{
				synchronized (serverChannel) {
					serverChannel.wait(60000);
				}
			}catch(InterruptedException e){}
		}
	}

	public void accept(AcceptHandler acceptCompletionHandler) {
		serverChannel.accept(this, acceptCompletionHandler);
	}

	@Override
	public void setIoAdaptor(IoAdaptor ioAdaptor) {
		acceptHandler = new AcceptHandler(ioAdaptor);
	}

	@Override
	public void close() throws IOException {
		if (serverChannel != null && serverChannel.isOpen()) {
			serverChannel.close();
		}
		ThreadPool.getAioPool().shutdown();
	}
	

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy