TcpServer.java 1.8 KB
package com.zhonglai.socket.html;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

/**
 * 基于JAVA AIO的,面向TCP/IP的,非阻塞式Sockect服务器框架类
 * 
 * @author zer0
 * @version 1.0
 * @date 2015-2-15
 */
public class TcpServer {
	

	private volatile Integer port;//服务器端口
	private Channel channel;
	private EventLoopGroup bossGroup;
	private EventLoopGroup workerGroup;

    private ChannelInitializer channelInitializer;

	public TcpServer(Integer port, ChannelInitializer channelInitializer){
		this.port = port;
		this.channelInitializer = channelInitializer;
	}

	/**
	 * 启动服务器
	 * 
	 * @author zer0
	 * @version 1.0
	 * @date  2015-2-19
	 */
	public ChannelFuture startServer(){

		bossGroup = new NioEventLoopGroup();
		workerGroup = new NioEventLoopGroup();
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workerGroup)
				 .channel(NioServerSocketChannel.class)
				 .childHandler(channelInitializer)
				.handler(new LoggingHandler(LogLevel.INFO))
				.option(ChannelOption.SO_BACKLOG, 128); // 设置tcp协议的请求等待队列
		try {
			ChannelFuture future = bootstrap.bind(new InetSocketAddress(port)).sync();
			channel = future.channel();


			System.out.println("服务器已启动,端口:" + port);
			return future;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void destory(){
		if (channel != null) {
			channel.close();
		}
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}

}