标签:netty
最近在学习netty相关知识,觉得《netty 权威指南》这本书还是挺好的,适合我这种初学者.加上netty本身自带的许多例子,学起来还是挺有兴趣的.简单记录下,
一般服务器代码如下:
public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new ObjectEchoServerHandler(), new MyServerHandler()); } }); // Bind and start to accept incoming connections. b.bind(port).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap 是一个启动工具类,childHandler()方法用于往里面加入处理channel的操作类,并初始化它们. ChannelPipeline用于链式管理内部的channel处理类.
b.bind(port).sync().channel().closeFuture().sync(); 这句话拆成下面两句好理解点:
b.bind(port).sync() ; 线程同步阻塞等待服务器绑定到指定端口,
...channel().closeFuture().sync() 成功绑定到端口之后,给channel增加一个 管道关闭的监听器并同步阻塞,直到channel关闭,线程才会往下执行,结束进程。
标签:netty
原文地址:http://blog.csdn.net/zhuyijian135757/article/details/37974195