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

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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题