Search code examples
javatcpnetty

Reading binary data from TCP clients using Netty


I'm trying get byte data from TCP client applications. Following the documentation of Netty project I found this code and use it in my system:

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());
                            
                   }
        }); 

But in my ServerHandler class I'm unable to find and call the method:

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

instead of the typical:

void channelRead (ChannelHandlerContext ctx, Object msg){}

Thanks in advance!


Solution

  • Just do cast...

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