Netty成功向客户端发送及接收16进制数据

发送16进制数据

Netty向客户端发送16进制数据时,需要将16进制字符串转为byte数组,再将byte数组写入到ByteBuf当中。

自定义发送数据格式类

import com.sunson.platform.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @ClassName NettyMessageEncoder
 * @Deacription TODO 自定义发送消息格式  发送16进制
 * @Author LiuDaGang
 * @Date 2021/3/11 19:19
 * @Version 1.0
 **/
public class MyEncoder  extends MessageToByteEncoder<String> {


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf byteBuf) throws Exception {
        //将16进制字符串转为数组
        byteBuf.writeBytes(hexString2Bytes(s));
    }
}
/**

	 * @Title:hexString2Bytes

	 * @Description:16进制字符串转字节数组

	 * @param src 16进制字符串

	 * @return 字节数组

	 */

	public static byte[] hexString2Bytes(String src) {

		int l = src.length() / 2;

		byte[] ret = new byte[l];

		for (int i = 0; i < l; i++) {

			ret[i] = (byte) Integer.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();

		}

		return ret;

	}

之后指定自定义格式
在这里插入图片描述

然后直接write就行了。
在这里插入图片描述
客户端接收数据

遇到的问题

也可以不用自定义发送消息类,直接在发送消息前直接写入到ByteBuf当中。

        //netty需要用ByteBuf传输
       ByteBuf bufff = Unpooled.buffer();
//        //对接需要16进制
       bufff.writeBytes(ByteUtil.hexString2Bytes(m));
        ctx.write(bufff);

此方法不要再指定任何encode,否则会发送一条转换成合并之后的消息。

使用了此方法,又指定了自定义encode,发送两个合并后的消息:
在这里插入图片描述

接收16进制数据

自定义接收消息类

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @ClassName MyDecoder
 * @Deacription TODO  netty接收对象转16进制
 * @Author LiuDaGang
 * @Date 2021/3/2 14:49
 * @Version 1.0
 **/

public class MyDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //创建字节数组,buffer.readableBytes可读字节长度
        byte[] b = new byte[byteBuf.readableBytes()];
         //复制内容到字节数组b
        byteBuf.readBytes(b);
        //字节数组转字符串
        String str = new String(b);

       // System.out.println(str);

        list.add(bytesToHexString(b));
    }

    public String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
        sTemp = Integer.toHexString(0xFF & bArray[i]);
        if (sTemp.length() < 2)
        sb.append(0);
        sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
        }

public static String toHexString1(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
        buffer.append(toHexString1(b[i]));
        }
        return buffer.toString();
        }

public static String toHexString1(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
        return "0" + s;
        } else {
        return s;
        }
        }

}

指定自定义接收消息类
在这里插入图片描述完成

首先,我们需要在Spring Boot项目中引入Netty的依赖: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.22.Final</version> </dependency> ``` 然后,我们需要编写一个Netty客户端类,用于连接服务器并发送16进制数据: ```java public class NettyClient { private final String host; private final int port; private Channel channel; public NettyClient(String host, int port) { this.host = host; this.port = port; } public void connect() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HexEncoder()); pipeline.addLast(new NettyClientHandler()); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); channel = future.channel(); channel.closeFuture().sync(); } finally { group.shutdownGracefully(); } } public void sendHexData(String hexData) { if (channel == null || !channel.isActive()) { throw new IllegalStateException("Connection is not active"); } channel.writeAndFlush(Unpooled.copiedBuffer(hexData, CharsetUtil.US_ASCII)); } } ``` 在上面的代码中,我们使用了HexEncoder类来将字符串转换为16进制数据,然后将它们发送到服务器。我们还使用了NettyClientHandler类来处理从服务器接收到的响应。 最后,我们可以在Spring Boot应用程序中使用这个Netty客户端类来发送16进制数据: ```java @RestController @RequestMapping("/api") public class NettyController { @GetMapping("/sendHexData") public String sendHexData(@RequestParam String hexData) throws Exception { NettyClient client = new NettyClient("localhost", 8080); client.connect(); client.sendHexData(hexData); return "OK"; } } ``` 在上面的代码中,我们可以使用sendHexData方法来发送16进制数据到服务器。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狂狂狂狂狂哉。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值