发送16进制数据

Netty向客户端发送16进制数据时,需要将16进制字符串转为byte数组,再将byte数组写入到ByteBuf当中。

public static byte[] hexString2Bytes(String src) {

        int l = src.length() / 2;

        byte[] ret = new byte[l];

        for (int i = 0; i < l; i++) {

            ret[i] = (byte) Integer.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();

        }

        return ret;

    }


public static String bytesToHexString(byte[] src) {
    StringBuilder stringBuilder = new StringBuilder("");
    if (src == null || src.length <= 0) {
        return null;
    }
    for (int i = 0; i < src.length; i++) {
        int v = src[i] & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            stringBuilder.append(0);
        }
        stringBuilder.append(hv);
    }
    return stringBuilder.toString();
}
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
       //Netty需要用ByteBuf传输
       ByteBuf bufff = Unpooled.buffer();
       //对接需要16进制
       bufff.writeBytes(ByteUtil.hexString2Bytes(m));
       ctx.writeAndFlush(bufff);

  }
      

接收16进制数据

public void channelRead(ChannelHandlerContext ctx, Object msg) {

    ByteBuf in = (ByteBuf) msg;
    byte[] bs = new byte[in.readableBytes()];
    in.readBytes(bs);
    String order = ByteUtil.bytesToHexString(bs);
    //todo 业务

}

Netty入门教程

总结

使用Netty向客户端发送消息,如果是16进制报文,需要把16进制报文转换成byte数组,然后再写入到ByteBuf中。

本文由博客一文多发平台 OpenWrite 发布!

程序员子龙
1 声望1 粉丝