通过重写channelRead(ChannelHandler ctx, Object msg) 方法读取c++发过来的字节数据。
public class ServerHandler extends ChannelHandlerAdapter{
public void channelRead(ChannelHandlerContext channel, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf)msg;
byte [] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);//复制内容到字节数组bytes
String hex = bytes2HexString(bs); //将byte数组转为16进制字符串
String str = hexString2String(hex,”GBK”); //将16进制字符串转换为普通字符串
System.out.println(str); //这里打印全是乱码
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(“异常:”,e);
}
}
private String bytes2HexString(byte[] b) {
StringBuffer result = new StringBuffer();
String hex;
for (int i = 0; i < b.length; i&#