开发者社区 问答 正文

netty使用mqtt解码器编码器,什么反应也没有?报错

public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new MqttDecoder());
                            ch.pipeline().addLast(new MqttEncoder());
                            ch.pipeline().addLast(new ClientInBoundHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(HOST, PORT).sync();
            future.channel().closeFuture().sync();
        }finally {
            worker.shutdownGracefully();
        }
    }



这是client端的代码,最上面是编码器和解码器

具体的handler代码是

@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_LEAST_ONCE, false, 0);
        MqttConnectMessage connectMessage = new MqttConnectMessage(fixedHeader, null, null);
        ctx.channel().writeAndFlush("connectMessage");

//        ByteBuf byteBuf = Unpooled.copiedBuffer("hello".getBytes());
//        ctx.writeAndFlush(byteBuf);
    }



问题1.我现在运行, server端那边什么都收不到. 我给server端的decode打断点, client的encode打断点都没有执行到, 也不知道是不是我断点打错了

2. 我把上面注释去掉 , server端能报错, 说协议有错误, 我觉得奇怪,为什么这样反而能收到?  



展开
收起
爱吃鱼的程序员 2020-06-10 15:18:12 1156 分享 版权
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    人呢人呢你确定是以debug方式启动程序的?确定啊。因为debug自己写的程序可以channelActive(ctx)这个方法时还没有完全按协议建议通讯吧回复<aclass='referer'target='_blank'>@zigzagroad:不是这个原因吧.可以用StringDecoder和StringEncoder试一下我这用的是netty4的版本,在channelRead0(ctx,msg)中正常解码。不过只是测试程序解决了吗 我也遇到了

    2020-06-10 15:18:29
    赞同 展开评论