记:Nett发送HEX值,转码后中文乱码问题

项目场景:

JAVA 使用NETTY框架建立socket数据通讯

问题描述:

服务端将定义好的字符串,转HEX值,回复到客户端,客户端将字符串转码解析后中文乱码
String strTo16 = HexUtils.strTo16(json.toString());

	public static String strTo16(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;
	}

服务端回复

ByteBuf resp = Unpooled.copiedBuffer(HexUtils.HexString2Buf(strTo16 ));
ChannelFuture writeAndFlush = ctx.writeAndFlush(resp);

HexString2Buf 方法

public static byte[] HexString2Buf(String src) {
		int len = src.length();
		byte[] ret = new byte[len / 2];
		byte[] tmp;
		try {
			tmp = src.getBytes("UTF-8");
			for (int i = 0; i < len; i += 2) {
				ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return ret;
	}
public static byte uniteBytes(byte src0, byte src1) {
		try {
			byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }, "UTF-8")).byteValue();
			_b0 = (byte) (_b0 << 4);
			byte _b1;
			_b1 = Byte.decode("0x" + new String(new byte[] { src1 }, "UTF-8")).byteValue();
			byte ret = (byte) (_b0 ^ _b1);
			return ret;
		} catch (Exception e) {
			return 0;
		}
	}

原因分析:

一直以为HexString2Buf 转 byte[]时 编码原因,所以tmp = src.getBytes(“UTF-8”);设置为UTF-8编码,但是不起作用,结果还是乱码
还是乱码


解决方案:

后来觉的是不是字符串转HEX值时没有定义编码的原因,所以将String转HEX方法修改为:

strTo16 = HexUtils.bytesToHexString(json.toString().getBytes("UTF-8"));

public static String bytesToHexString(byte... src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

调试代码,果然成功了
操作成功

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个很好的问题。使用Spring Boot和Netty实现双向通信的过程如下: 1. 首先,在pom.xml中添加以下依赖项: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency> ``` 2. 创建Netty服务器 ``` @Component public class NettyServer { private final EventLoopGroup bossGroup = new NioEventLoopGroup(); private final EventLoopGroup workerGroup = new NioEventLoopGroup(); private Channel channel; @Autowired private NettyServerHandler nettyServerHandler; public void start() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(nettyServerHandler); } }); ChannelFuture f = bootstrap.bind(8888).sync(); if (f.isSuccess()) { System.out.println("Netty server start success"); } channel = f.channel().closeFuture().sync().channel(); } public void stop() throws Exception { channel.close(); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } ``` 在这个示例中,我们创建了一个名为NettyServer的类。这个类使用了Netty的ServerBootstrap类来创建服务器。在服务器启动时,我们需要指定使用的IO模式和端口号。此外,我们还需要指定NettyServerHandler类,这个类用于处理客户端发来的消息。 3. 创建NettyServerHandler类 ``` @Component @ChannelHandler.Sharable public class NettyServerHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Server received:" + msg); // 回复客户端 ctx.writeAndFlush("Server received your message: " + msg + "\n"); // 其他业务逻辑 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Server exceptionCaught"); cause.printStackTrace(); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Server channelActive"); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("Server channelInactive"); super.channelInactive(ctx); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("Server channelReadComplete"); super.channelReadComplete(ctx); } } ``` 在这个示例中,我们创建了一个名为NettyServerHandler的类。这个类用于处理客户端发来的消息。我们需要实现channelRead0方法,这个方法会在客户端发送消息时被调用。在这个方法中,我们可以处理客户端发送的消息,并且回复消息给客户端。除此之外,我们还需要实现其他方法,如exceptionCaught、channelActive、channelInactive和channelReadComplete。 4. 创建Netty客户端 ``` @Component public class NettyClient { private Channel channel; private final EventLoopGroup group = new NioEventLoopGroup(); @Autowired private NettyClientHandler nettyClientHandler; public void start() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(nettyClientHandler); } }); ChannelFuture f = bootstrap.connect("localhost", 8888).sync(); if (f.isSuccess()) { System.out.println("Netty client start success"); } channel = f.channel().closeFuture().sync().channel(); } public void stop() throws Exception { channel.close(); group.shutdownGracefully(); } } ``` 在这个示例中,我们创建了一个名为NettyClient的类。这个类使用了Netty的Bootstrap类来创建客户端。在客户端启动时,我们需要指定使用的IO模式和服务器的IP地址和端口号。此外,我们还需要指定NettyClientHandler类,这个类用于处理服务器发来的消息。 5. 创建NettyClientHandler类 ``` @Component @ChannelHandler.Sharable public class NettyClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Client received:" + msg); // 其他业务逻辑 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Client exceptionCaught"); cause.printStackTrace(); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client channelActive"); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client channelInactive"); super.channelInactive(ctx); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("Client channelReadComplete"); super.channelReadComplete(ctx); } } ``` 在这个示例中,我们创建了一个名为NettyClientHandler的类。这个类用于处理服务器发来的消息。我们需要实现channelRead0方法,这个方法会在服务器发送消息时被调用。在这个方法中,我们可以处理服务器发送的消息。除此之外,我们还需要实现其他方法,如exceptionCaught、channelActive、channelInactive和channelReadComplete。 6. 在Spring Boot中启动Netty服务器和客户端 最后,在Spring Boot应用程序的启动类中,我们需要启动Netty服务器和客户端。我们可以使用@PostConstruct注释来启动Netty服务器和客户端。 ``` @SpringBootApplication public class Application { @Autowired private NettyServer nettyServer; @Autowired private NettyClient nettyClient; @PostConstruct public void start() throws Exception { new Thread(() -> { try { nettyServer.start(); } catch (Exception e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { nettyClient.start(); } catch (Exception e) { e.printStackTrace(); } }).start(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 好了,以上就是使用Spring Boot和Netty实现双向通信的全部过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值