美文网首页
Netty模型

Netty模型

作者: Cook1fan | 来源:发表于2021-04-17 16:43 被阅读0次
image.png
@Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 比如这里我们有一个非常耗时长的业务 - 异步执行 - 提交该 channel 对应的
        // NIOEventLoop 的 taskQueue 中,
        // 解决方案1 用户程序自定义的普通任务
        ctx.channel().eventLoop().execute(() -> {
            try {
                Thread.sleep(10 * 1000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(耗时1)", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                System.out.println("发生异常:" + e.getMessage());
            }
        });
        ctx.channel().eventLoop().execute(() -> {
            try {
                Thread.sleep(20 * 1000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(耗时3)", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                System.out.println("发生异常:" + e.getMessage());
            }
        });
        // 用户自定义定时任务 - 该任务是提交到 scheduleTaskQueue 中
        ctx.channel().eventLoop().schedule(() -> {
            try {
                Thread.sleep(5 * 1000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(耗时2)", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                System.out.println("发生异常:" + e.getMessage());
            }
        }, 5, TimeUnit.SECONDS);
        System.out.println("go on...");

        /*

        System.out.println("服务器读取线程:" + Thread.currentThread().getName());
        System.out.println("server ctx = " + ctx);
        System.out.println("看看 channel 和 pipeline 的关系");
        Channel channel = ctx.channel();
        ChannelPipeline pipeline = ctx.pipeline(); // 本质是一个双向链表,出战入栈问题
        // 将 msg 转成一个 ByteBuf
        // ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端发送的消息是:" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址:" + channel.remoteAddress());

        */

    }
image.png
image.png
image.png
image.png
image.png
image.png

相关文章

网友评论

      本文标题:Netty模型

      本文链接:https://www.haomeiwen.com/subject/hnnklltx.html