java socket定长报文实现接口通信

 因为要和银行方进行通信,所以接口通信传参就需要实现定长报文,小小的吐槽一下,最开始是json传参方式到改为xml,刚写好xml还没有试试就通知要改为定长报文,也就我脾气好,真想骂爹,骂娘,但是时间有限还是得实现啊,但是网上资料又不多,最终一点点摸索弄出来了。

首先定长报文是指像json格式那种key,value有字段有值的方式,定长报文就是String拼接的vlaue值,而没有key了,那么你就想了那我解析值或者取值怎么取我想要的对应的值呢,其实定长报文么,顾名思义就是没有了key就把值的长度固定了呀,举个例子:

json:{"id":1,"name":"张三"}

定长报文:000001           张三

看出来了么,我把id的长度定为6,name的长度定为15,那么我取id的值就是从0-6,取name的时候就是从6-21就可以了,取功能说完了,那存呢,存就要得把所有的数据拼成String长字符串,但是规定数字要补0,字符串前要补空格,那怎么办呢?别急,我有办法

1.生成定长报文

实现:把所有的要生成的参数定义为实体,并利用自己写的注解的方式说明每个字段的长度,并表明是要补齐空格还是补0

实体如下

public class BankClaimBody {
    @PadRightWithSpace(len = 8)
    private String storeId;
    @PadRightWithSpace(len = 20)
    private String applyTime;

    public String getStoreId() {
        return storeId;
    }

    public void setStoreId(String storeId) {
        this.storeId = storeId;
    }
    public String getApplyTime() {
        return applyTime;
    }

    public void setApplyTime(String applyTime) {
        this.applyTime = applyTime;
    }
}

@PadRightWithSpace 就是补齐空格的注解

package report.fixed.demo.socketfixed.bodyhadle;

import java.lang.annotation.*;

/**
 * 左对齐右边补空格
 *
 *
 */
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PadRightWithSpace {
	int len() default 0;
}

@PadLeftWithZero 的注解类就是补0的操作

@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PadLeftWithZero {
	int len() default 0;
}

@NoNeedPack 没有注解的情况

@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoNeedPack {
}

生成定长报文测试一下

 public static void main(String[] args) throws Exception {
    BankClaimBody body =new  BankClaimBody();
    body.setStoreId("02222222");
    body.setApplyTime(”2020-02-03“);
    // 生成定长报文
    String strpj = MessageHelper.createFiexdLengthMsg(body,
    body.getClass());
    // 打开socket连接并传输定长报文数据
    String data = SocketClient.openSendMsg(strpj);
 }

发下生成定长报文的工具类

 public static String createFiexdLengthMsg(Object obj, Class<?> clazz) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        StringBuffer sb = new StringBuffer();
        for (Field field : fields) {
            if (field.isAnnotationPresent(PadRightWithSpace.class)) {// 如果是左对齐,右边补空格注解
                PadRightWithSpace padRightWithSpace = field.getAnnotation(PadRightWithSpace.class);
                int len = padRightWithSpace.len();
                field.setAccessible(true);
                String newValue = padRightWithSpace((String) field.get(obj), len);
                field.set(obj, newValue);
            } else if (field.isAnnotationPresent(PadLeftWithZero.class)) {// 如果是右对齐,左边补0注解
                PadLeftWithZero padLeftWithZero = field.getAnnotation(PadLeftWithZero.class);
                int len = padLeftWithZero.len();
                field.setAccessible(true);
                String newValue = padLeftWithZero((String) field.get(obj), len);
                field.set(obj, newValue);
            }

            String value = (String) field.get(obj);
            sb.append(value);
        }
        String msgBody = sb.toString();
        //String msgHead = padLeftWithZero(String.valueOf(msgBody.getBytes("GBK").length), 4);
        return msgBody;
    }


   public static String padRightWithSpace(String orgStr, int len) {
        if (orgStr == null) {
            orgStr = "";
        }
        int length = 0;
        try {
            if (orgStr.getBytes("GBK").length >= len) {
                return orgStr;
            }

            length = orgStr.getBytes("GBK").length;
        } catch (UnsupportedEncodingException e) {
        }

        StringBuffer sb = new StringBuffer(orgStr);
        // 准确的字节长度拿到后 再据此补位
        for (int j = 0; j < len - length; j++) {
            sb.append(" ");
        }
        return sb.toString();
    }

    private static String padLeftWithZero(String orgStr, int len) {
        if (orgStr == null) {
            orgStr = "";
        }
        int length = orgStr.length();
        if (length >= len) {
            return orgStr;
        }

        StringBuffer sb = new StringBuffer(orgStr);
        // 准确的字节长度拿到后 再据此补位
        for (int j = 0; j < len - length; j++) {
            sb.insert(0, "0");
        }
        return sb.toString();
    }

再发下socket连接发送请求操作

package report.fixed.demo.socketfixed.soketclient;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @ClassName : SocketClient
 * @Description :
 * @Author : df
 * @Date: 2021-03-23 13:04
 */
public class SocketClient {
    private static Socket socket; //socket连接
    private static boolean connection = false;//socket是否连接
    private static int connectcount = 0;
    private static String ip = "22.16.219.91";
    //private static String ip = "localhost";
    private static Integer port = 9004;
    //private static Integer port = 8888;

    /*
     * @Author df
     * @Description /打开连接并发送数据
     * @Date 13:10 2021/3/23
     **/
    public static String openSendMsg(String sendData) {
        // 打开连接
        open();
        if (connection == false) {
            return null;
        }
        // 发送报文并获取返回报文
        String resultData = sendAndRecMsg(sendData.getBytes());
        close();
        return resultData;
    }

    /*
     * @Author df
     * @Description 发送数据
     * @Date 13:11 2021/3/23
     **/
    public static String sendAndR
评论 19
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值