Netty服务器端代码,高并发

 

package 
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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 io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

public class NettyServer extends AbstractIoService {
	
	private int port = 8800;
	
	private static final InternalLogger LOG = InternalLoggerFactory.getInstance(NettyServer.class);
	
	private EventLoopGroup bossGroup = new NioEventLoopGroup(2, new DefaultThreadFactory("server1", true));
	private EventLoopGroup workerGroup = new NioEventLoopGroup(4, new DefaultThreadFactory("server2", true));
	
	public NettyServer(String name, int port, AbstractChannelInitializer channelInitializer, AbstractChannelHandlerAdapter channelHandler) {
		super(name, channelInitializer, channelHandler);
		this.port = port;
	}
	
	@Override
	public void start() {
		try {
			ServerBootstrap bootStrap = new ServerBootstrap();
			// the parent (acceptor) and the child (client)
			bootStrap.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 1024)
					.option(ChannelOption.TCP_NODELAY, true)
					.handler(new LoggingHandler(LogLevel.INFO))
					.childHandler(channelInitializer);
			
			ChannelFuture channelFuture = bootStrap.bind(port).sync();
			if (channelFuture.isSuccess()) {
				LOG.info("listen port {} success", port);
			}
			channelFuture.addListener(new ChannelFutureListener() {
				
				public void operationComplete(ChannelFuture future) throws Exception {
					// TODO Auto-generated method stub
					 LOG.info("##启动完成,刷新客户端存活状态。++++++++++");
					 if (future.isSuccess()) {
                    	 LOG.info("##启动完成,刷新客户端存活状态。");
           
                     } else {
                    	 LOG.error("#E#客户端启动失败。");
                    	 future.cause().printStackTrace();
                         LOG.error(future.cause().getMessage());
                     }	
				}
			});

               

			channelFuture.channel().closeFuture().sync();
			
//			f.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		}  finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
	}
	
	@Override
	public void close() {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值