Netty向客户端发送及接收16进制数据
# 发送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();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//Netty需要用ByteBuf传输
ByteBuf bufff = Unpooled.buffer();
//对接需要16进制
bufff.writeBytes(ByteUtil.hexString2Bytes(m));
ctx.writeAndFlush(bufff);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 接收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 业务
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 总结
使用Netty向客户端发送消息,如果是16进制报文,需要把16进制报文转换成byte数组,然后再写入到ByteBuf中。
上次更新: 2024/06/14, 13:58:29