长沙大猫 2016-03-20 15:01 采纳率: 0%
浏览 11519

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;
}
}

如需要更详细代码请回复跟帖  我跟帖告诉
  • 写回答

3条回答

  • nebulae__ 2016-03-21 09:52
    关注

    使用.getBytes("UTF-8);

    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试