hello netty

netty 构建Reactor主从多线程模型

netty版本

<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.68.Final</version>
</dependency>

启动类

public static void main(String[] args) throws InterruptedException {
        // 主线程 不从事工作,分派工作
        NioEventLoopGroup parent = new NioEventLoopGroup();
        // 从线程 从事工作
        NioEventLoopGroup child = new NioEventLoopGroup();
        try {
            // 启动
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parent, child) // 设置主从
                    .channel(NioServerSocketChannel.class)// 设置nio双向通道
                    .childHandler(new HelloServerInit());// 自处理器
            // 绑定端口 同步等待启动
            ChannelFuture channelFuture = serverBootstrap.bind(8011).sync();
            // 监听时间,同步
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 关闭
            parent.shutdownGracefully();
            child.shutdownGracefully();
        }
    }

自定义处理器

public class HelloServerInit extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        // 通过chanel 获取通道
        ChannelPipeline pipeline = socketChannel.pipeline();
        // 设置编解码助手类
        pipeline.addLast("HttpServerCodec",new HttpServerCodec());
        // 设置自定义的助手类
        pipeline.addLast("ConsumeHandler",new ConsumeHandler());
    }
}

自定义助手类

public class ConsumeHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext context, HttpObject obj) throws Exception {
        Channel channel = context.channel();
        if (obj instanceof HttpRequest) {
            // 获取客户端ip
            System.out.println(channel.remoteAddress());
            // 设置数据以及编码
            ByteBuf content = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);
            // 设置数据并设置请求头信息
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            // 写入并刷新
            context.writeAndFlush(response);
        }
    }
}

访问方式
1、浏览器直接访问 localhost:端口
在这里插入图片描述
2、linux curl ip:端口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值