z15918320
长沙大猫
采纳率0%
2016-03-20 15:01 阅读 10.2k

netty服务端接收到中文通信乱码问题

不多说 问题如题
以下是服务端代码
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("服务器接收到消息:" + body);
ctx.writeAndFlush(getSendByteBuf("服务器发送的数据APPLE"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException {

    byte[] req = message.getBytes("UTF-8");
    ByteBuf pingMessage = Unpooled.buffer();
    pingMessage.writeBytes(req);

    return pingMessage;
}

以下是客户端代码
public void channelActive(ChannelHandlerContext ctx) throws Exception {
byte[] data = "服务器,给我一个APPLE".getBytes();
firstMessage=Unpooled.buffer();
firstMessage.writeBytes(data);
ctx.writeAndFlush(firstMessage);

}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
System.out.println("客户端收到服务器数据:" + rev);
}
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}

如需要更详细代码请回复跟帖  我跟帖告诉
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • u012155923 咖啡不加盐 2016-03-20 15:27

    编码统一强转为uyf8

    点赞 评论 复制链接分享
  • qq_23018915 nebulae__ 2016-03-21 09:52

    使用.getBytes("UTF-8);

    点赞 评论 复制链接分享

相关推荐