第1步 自定义编码器以及编码格式
@Override
protected void initChannel(Channel ch) throws Exception {
// ChannelOutboundHandler,依照逆序执行
//ch.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.CHARSET_UTF_8));
// 属于ChannelInboundHandler,依照顺序执行
//ch.pipeline().addLast("decoder", new StringDecoder());
/**
* 自定义ChannelInboundHandlerAdapter
*/
// 基于换行符号
//ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
// 解码转String,注意调整自己的编码格式GBK、UTF-8
ch.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
ch.pipeline().addLast(new BootNettyChannelInboundHandlerAdapter());
}
自定义编码器时,这个一句为关键配置
ch.pipeline().addLast(new StringDecoder(Charset.forName(“GBK”)));
第2步 在channelRead中进行解码并且按照约定的编码集
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception, IOException {
String str = new String(msg.toString().getBytes("GBK"));
String body = HexUtil.encodeHexStr(str).toUpperCase();
System.out.println("buf:" + body);
}
String body = HexUtil.encodeHexStr(bytes).toUpperCase();
此句使用Hutool插件!