赞
踩
全文详见个人独立博客:Netty4自学笔记 (3) - Netty NIO Server和Client 样例说明
欢迎加入群聊,一起交流探讨:【Java学习交流(982860385)】
更新节奏缓慢,因为每晚学习注意力不够集中,学习进展缓慢。本还给自己找了一大堆其他理由,但摸着良心问自己,似乎只有这个理由说的通。
想搞懂的太多,却始终没搞明白。先看一个用Netty编写的NIO Server的样例。
- package com.coderli.nettylab.guide;
-
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
-
- /**
- * @author lihongzhe 2018/7/24 23:19
- * @site https://www.coderli.com
- */
- public class NettyNioServer {
-
- public static void main(String[] args) throws InterruptedException {
- EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap(); // (2)
- b.group(bossGroup, workerGroup)
- .channel(NioServerSocketChannel.class) // (3)
- .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new ServerHandler());
- }
- })
- .option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true);
-
- ChannelFuture f = b.bind(7060).sync(); // (5)
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
-
- }
-
ServerHanler代码
- package com.coderli.nettylab.guide;
-
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
-
- /**
- * @author lihongzhe 2018/7/24 23:58
- * @site https://www.coderli.com
- */
- public class ServerHandler extends ChannelInboundHandlerAdapter {
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- System.out.println("Receive Msg.");
- ((ByteBuf) msg).release();
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- cause.printStackTrace();
- ctx.close();
- }
- }
上述代码改自Netty官方手册。NettyNioServer代码中做了几处标记,分别对应我们在Netty4 自学笔记(2)中讨论的关键点,简析如下:
全文详见个人独立博客:
Netty4自学笔记 (3) - Netty NIO Server和Client 样例说明
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。