通过重写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++) {
hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
result.append(hex.toUpperCase());
}
return result.toString();
}
private String hexString2String(Stirng hex, String charset) {
byte[] bs = new byte[hex.length()/2];
for(int i=0; i<bs.length; i++) {
bs[i] = (byte)(0xff&Integer.parseInt(hex.substring(i*2,i*2+2),16));
}
try{
hex = new String(bs, charset);
}catch(Exception e) {
e.printStackTrace();
}
return hex;
}
}