1

I'm using Netty 4 to communicate with a GPS device which sends data in HEX. The problem is that in Netty I'm receiving some weird messages($$..0.....@..y..) instead of the HEX data(00 00 19 40 00 02 79 1d 0d 0a) I'm supposed to read. The method I'm using to handle the messages is quite simple:

 public void channelRead(ChannelHandlerContext ctx, Object msg) {

    ByteBuf in = (ByteBuf) msg;
    String message = in.toString(io.netty.util.CharsetUtil.US_ASCII);
}

And this is my main method:

 public static void main(String args[]) {


    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch)
                            throws Exception {
                        ch.pipeline().addLast(new GpsMessageHandler());
                    }
                })

                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).await();

        f.channel().closeFuture().syncUninterruptibly();

    }

    catch (Exception e) {
    }

    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

Any help will be appreciated.

Khalil Aouachri
  • 199
  • 3
  • 14
  • 1
    The text you get is the hex data converted to ASCII. You would want to read the *bytes* from the byte buffer and [convert it to hex as needed](http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java). – nanofarad Jun 19 '15 at 12:06
  • 1
    Hex values are nothing other than bytes in a specific representation (Hex). You are converting the bytes to text using the ASCII charset. Try converting each byte of ther buffer using: String.format("%02X ", byte) – ssindelar Jun 19 '15 at 12:07
  • Thank you guys. Problem solved! – Khalil Aouachri Jun 20 '15 at 14:30

0 Answers0