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

相关推荐
探索java10 小时前
Netty Channel详解:从原理到实践
java·后端·netty
你打代码的样子真帅2 天前
从零开始构建物联网设备管理系统:基于Netty的高性能IoT平台实战
物联网·netty
9527出列7 天前
探索服务端启动流程
netty·源码阅读
深圳蔓延科技9 天前
NioEventLoopGroup 完全指南
netty
深圳蔓延科技10 天前
如何使用 Netty 实现 NIO 方式发送 HTTP 请求
netty
Derek_Smart16 天前
Netty 客户端与服务端选型分析:下位机连接场景
spring boot·后端·netty
Derek_Smart18 天前
工业级TCP客户端高可靠连接架构设计与Netty优化实践
java·性能优化·netty
c_zyer19 天前
FreeSWITCH与Java交互实战:从EslEvent解析到Spring Boot生态整合的全指南
spring boot·netty·freeswitch·eslevent
Derek_Smart22 天前
工业物联网千万级设备通信优化:Netty多帧解码器实战,性能提升
java·性能优化·netty
皮皮林5511 个月前
Netty 超详细解答十问十答
netty