问题遇到的现象和发生背景
netty server怎么判断客户端传来的是hex(16进制)还是plain(字符串)?
背景:有一个netty server用于接入物联网设备的tcp连接,有些设备使用字符串传输,有些设备使用16进制传输,公司目前的做法是netty server根据设备端口号来判断接收的数据到底以什么方式显示。我想问下还有没有其他的办法了?
用代码块功能插入代码,请勿粘贴截图
public class TestPro extends StringDecoder {
public static AttributeKey<String> t1 = AttributeKey.newInstance("type");
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
if (ctx.channel().attr(t1).get().equals("hex")) {
String HEXES = "0123456789ABCDEF";
byte[] req = new byte[msg.readableBytes()];
msg.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());
} else {
super.decode(ctx, msg, out);
}
}
}