qq_29022421
2020-09-11 09:30
采纳率: 100%
浏览 828
已采纳

java netty与c++使用socket tcp协议通信,c++作为客户端,java作为服务端使用的是netty,接收字节数据,先将字节转16进制字符串再转为普通字符串,中英文全出现乱码。求急大神,谢谢!

通过重写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;
    }   

}

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

5条回答 默认 最新

相关推荐 更多相似问题