Netty向客户端发送和接收16进制数据
发送16进制数据
Netty向客户端发送16进制数据时,需要将16进制字符串转为byte数组,再将byte数组写入到ByteBuf当中。
自定义发送数据格式类
import com.sunson.platform.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* @ClassName NettyMessageEncoder
* @Deacription TODO 自定义发送消息格式 发送16进制
* @Author LiuDaGang
* @Date 2021/3/11 19:19
* @Version 1.0
**/
public class MyEncoder extends MessageToByteEncoder<String> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf byteBuf) throws Exception {
//将16进制字符串转为数组
byteBuf.writeBytes(hexString2Bytes(s));
}
}
/**
* @Title:hexString2Bytes
* @Description:16进制字符串转字节数组
* @param src 16进制字符串
* @return 字节数组
*/
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;
}
之后指定自定义格式
然后直接write就行了。
客户端接收数据
遇到的问题
也可以不用自定义发送消息类,直接在发送消息前直接写入到ByteBuf当中。
//netty需要用ByteBuf传输
ByteBuf bufff = Unpooled.buffer();
// //对接需要16进制
bufff.writeBytes(ByteUtil.hexString2Bytes(m));
ctx.write(bufff);
此方法不要再指定任何encode,否则会发送一条转换成合并之后的消息。
使用了此方法,又指定了自定义encode,发送两个合并后的消息:
接收16进制数据
自定义接收消息类
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* @ClassName MyDecoder
* @Deacription TODO netty接收对象转16进制
* @Author LiuDaGang
* @Date 2021/3/2 14:49
* @Version 1.0
**/
public class MyDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
//创建字节数组,buffer.readableBytes可读字节长度
byte[] b = new byte[byteBuf.readableBytes()];
//复制内容到字节数组b
byteBuf.readBytes(b);
//字节数组转字符串
String str = new String(b);
// System.out.println(str);
list.add(bytesToHexString(b));
}
public String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static String toHexString1(byte[] b) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; ++i) {
buffer.append(toHexString1(b[i]));
}
return buffer.toString();
}
public static String toHexString1(byte b) {
String s = Integer.toHexString(b & 0xFF);
if (s.length() == 1) {
return "0" + s;
} else {
return s;
}
}
}
指定自定义接收消息类
完成