【问题标题】:Reading binary data from TCP clients using Netty使用 Netty 从 TCP 客户端读取二进制数据
【发布时间】:2014-12-01 02:29:03
【问题描述】:

我正在尝试从 TCP 客户端应用程序获取字节数据。根据 Netty 项目的文档,我找到了这段代码并在我的系统中使用它:

ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
  
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                   ChannelPipeline p = ch.pipeline();
                   p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                   p.addLast("bytesDecoder", new ByteArrayDecoder());
                   p.addLast(new ServerHandler());
                            
                   }
        }); 

但在我的 ServerHandler 类中,我无法找到并调用该方法:

void channelRead (ChannelHandlerContext ctx, byte[] bytes){}

而不是典型的:

void channelRead (ChannelHandlerContext ctx, Object msg){}

提前致谢!

【问题讨论】:

    标签: java tcp netty


    【解决方案1】:

    只需投射...

    void channelRead (ChannelHandlerContext ctx, Object msg){
        byte[] bytes = (byte[]) msg;
    }
    

    【讨论】:

    • 好的,谢谢,但是出于什么原因我需要将处理程序p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));p.addLast("bytesDecoder", new ByteArrayDecoder()); 添加到管道中?如果只是做演员?
    • 因为否则你将不会收到一个 byte[] 而是一个 ByteBuffer
    • 感谢您的回答,感谢您开发 Netty 是一个了不起的框架 :)
    猜你喜欢
    • 2020-01-28
    • 2021-09-05
    • 2019-07-27
    • 2017-04-15
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2012-05-26
    相关资源
    最近更新 更多