netty客户端向服务器发送十六进制数据

最近项目需要实现java向终端发送报文,终端只接受十六进制数据,学了下netty但是在开发中还是遇到无法发送,最终找到是因为发送字符串的编解码设置不对导致的

1、在ClientInitializer类中设置发送、接受的字符串格式

image.png

最初是通过StringDecoder()、StringEncoder()进行编码设置的,导致终端接受的报文无法解析;
需要通过自定义发送消息格式、接收消息格式,如下

public class ClientInitializer extends ChannelInitializer<SocketChannel> {
    private CountDownLatch lathc;

    public ClientInitializer(CountDownLatch lathc) {
        this.lathc = lathc;
    }
    private ClientHandler handler;

    @Override
    protected void initChannel(SocketChannel sc) throws Exception {
        handler = new ClientHandler(lathc);
     
        sc.pipeline().addLast("encoder",new MyEncoder()); //自定义发送消息格式(16进制数据)
        sc.pipeline().addLast("decoder",new MyDecoder()); //自定义接收消息格式(16进制数据)

        sc.pipeline().addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
        sc.pipeline().addLast(new ReadTimeoutHandler(60));//设置超时时间

        sc.pipeline().addLast(handler);
    }
 }
复制代码

2、自定义发送消息格式MyEncoder

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

    /**
     * @param src 16进制字符串
     * @return 字节数组
     * @Title:hexString2Bytes
     * @Description:16进制字符串转字节数组
     */

    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;
    }
}
复制代码

3、自定义接收消息格式MyDecoder

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);
        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;
        }
    }
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享