netty入门例子

netty封装了java的nio。开发只需要按照netty提供的api方法,相对繁琐nio使开发变的相对简单很多。

服务端启动

复制代码
//创建两个线程池
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
//boot启动类
ServerBootstrap boot = new ServerBootstrap();
//绑定线程池,channel类型为NioServerSocketChannel
boot.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
               //添加pipeline
                channel.pipeline()
                        .addLast(new StringDecoder())
                        .addLast(new StringEncoder())
                        .addLast(new ChatServerHandler());
            }
        });
System.out.println("server start");
//绑定端口
ChannelFuture future = boot.bind(9000).sync();

ChatServerHandler就是简单继承SimpleChannelInboundHandler,重写channelRead0方法。

复制代码
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        System.out.println(s);
    }
}

客户端启动

复制代码
//创建线程组
EventLoopGroup group = new NioEventLoopGroup();
//启动类
Bootstrap boot = new Bootstrap();
//绑定线程组,设置channel类型为NioSocketChannel
boot.group(group).channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                //初始化pipeline
                channel.pipeline()
                        .addLast(new StringEncoder())
                        .addLast(new StringDecoder());
            }
        });
        //连接server
ChannelFuture future = boot.connect("localhost", 9000).sync();
Channel channel = future.channel();
//发送数据
channel.writeAndFlush("hi");
channel.closeFuture().sync();
group.shutdownGracefully();

服务端能收到客户端发送数据。

线程模型

使用reactor线程模型处理channel事件。

线程组:

线程组的创建通过NioEventLoopGroup类,可以入参指定线程组内child数量,不指定会根据当前机器的CPU进行计算child数量。每个child是一个NioEventLoop实例。NioEventLoop是一个单线程线程池类。

线程组内监听到Selector事件都会交由channel绑定的pipeline进行处理。

BossGroup:负责创建serverchannel,并且处理client连接事件,也就是accept事件。然后将新建的client连接与workGroup线程池进行绑定

workGroup:负责监听已绑定channel连接的读写事件。

参考:

https://www.alibabacloud.com/blog/essential-technologies-for-java-developers-io-and-netty_597367

相关推荐
安徽杰杰1 小时前
智慧充电:新能源汽车智慧充电桩的发展前景受哪些因素影响?
netty
漫步者TZ5 天前
【Netty系列】解决TCP粘包和拆包:LengthFieldBasedFrameDecoder
java·网络协议·tcp/ip·netty
安徽杰杰5 天前
智慧赋能:移动充电桩的能源供给革命与便捷服务升级
netty
安徽杰杰5 天前
智慧赋能:新能源汽车充电桩应用现状与管理升级方案
netty
触角云科技9 天前
智慧充电桩数字化管理平台:环境监测与动态数据可视化技术有哪些作用?
netty
猫咪老师QAQ10 天前
Netty 实战篇:Netty RPC 框架整合 Spring Boot,迈向工程化
netty
猫咪老师QAQ10 天前
Netty 实战篇:为 Netty RPC 框架引入调用链追踪,实现链路透明化
netty
漫步者TZ10 天前
【Netty系列】实现HTTP文件服务器
http·网络编程·netty
猫咪老师QAQ11 天前
Netty 实战篇:构建简易注册中心,实现服务发现与调用路由
netty
触角云科技11 天前
充电便捷,新能源汽车移动充电服务如何预约充电
netty