Netty接收的数据为HEX,如何处理?
在物联网通信中,设备上传的数据通常为hex类型,若我们服务端使用Netty接收数据,会出现乱码的情况。
- 自定义解码器
public class ReceiveDecode extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
String HEXES = "0123456789ABCDEF";
byte[] req = new byte[in.readableBytes()];
in.readBytes(req);
final StringBuilder hex = new StringBuilder(2 * req.length);
for (int i = 0; i < req.length; i++) {
byte b = req[i];
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F)));
}
out.add(hex.toString());
}
}
使用Hex解码算法,对Hex类型数据进行解码,转换为真正数据。
- 使用自定义解码器
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ReceiveDecode());
pipeline.addLast(new DtuInboundHandler());
}
}
- 使用SimpleChannelInboundHandler进行入站处理
@Component
@ChannelHandler.Sharable
public class DtuInboundHandler extends SimpleChannelInboundHandler<Object> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
String message = (String) msg;
log.info("接收到的数据:" + message);
// 处理接收的数据....
}
}
因为SimpleChannelInboundHandler可以实现了对资源的自动释放,因此,此处继承SimpleChannelInboundHandler构建入站处理器。同样,也可以使用ChannelInboundHandler构建入站处理器,但是需要记得手动释放资源。