java之tcp拆包代码

背景

对tcp传输的数据按结尾字符*进行拆包,实际传输的内容是json格式的数据。包括测试代码,如果有错误,敬请指出,谢谢!

代码

package com.example.demo;

import com.alibaba.fastjson.JSONObject;
import com.ctc.wstx.util.StringUtil;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * tcp拆包
 *

 * @date 2021/9/3 11:08
 */
public class aa {
    private static String prefix = "";

    public static void main(String[] args) {
        String aa[] = new String[5];
        //1.测试数据不完整的情况,但是开头是完整的
        aa[0] = "{\"aabbcc\":\"1001\"}*{\"aabbcc\":\"1\"}*{\"clien";
        aa[1] = "tId\":\"1\"}*{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic_pressure\":0,\"timestamp\":1635325129}*";
        aa[2] = "tId\":\"1\"}*{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic_pressure\":0,\"timestamp\":1635325129}*";
        aa[3] = "{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic_pressure\":0,\"timestamp\":1635325129}*{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic";
        aa[4] = "_pressure\":0,\"timestamp\":1635325129}*{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic_pressure\":0,\"timestamp\":1635325129}*{\"aabbcc\"";
        System.out.println("=================情况1=================");
        System.out.println("预计丢失数据=================【tId\":\"1\"}】");
        test(aa);
        //2.测试数据开头不完整,需要丢掉
        aa[0] = "{\"aabbcc\":\"1*{\"aabbcc\":\"1001\"}*{\"aabbcc\":\"1\"}*{\"clien";
        aa[1] = "{\"aabbcc\":\"1001\"}*{\"aabbcc\":\"1\"}*{\"clien";
        aa[2] = "tId\":\"1\"}*{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic_pressure\":0,\"timestamp\":1635325129}*";
        aa[3] = "{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic_pressure\":0,\"timestamp\":1635325129}*{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic";
        aa[4] = "_pressure\":0,\"timestamp\":1635325129}*{\"move\":0,\"aa\":0,\"s\":0,\"bb\":0,\"id\":10,\"p\":10,\"t\":7,\"h\":70,\"lic_pressure\":0,\"timestamp\":1635325129}*{\"aabbcc\"";
        System.out.println("=================情况2=================");
        System.out.println("预计丢失数据=================【{\"aabbcc\"{\"aabbcc\":\"1】");
        test(aa);
        //3.测试完整数据
        aa[0] = "{\"aabbcc\":\"1\"}*";
        aa[1] = "{\"aabbcc\":\"1\"}*";
        aa[2] = "{\"aabbcc\":\"1\"}*";
        aa[3] = "{\"aabbcc\":\"1\"}*";
        aa[4] = "{\"aabbcc\":\"1\"}*";
        System.out.println("=================情况3=================");
        test(aa);
        //4.测试完整数据多条
        aa[0] = "{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*";
        aa[1] = "{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*";
        aa[2] = "{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*";
        aa[3] = "{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*";
        aa[4] = "{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*{\"aabbcc\":\"1\"}*";
        System.out.println("=================情况4=================");
        test(aa);


    }

    private static void test(String[] aa) {
        int a = 1;
        for (String json : aa) {
            System.out.println("第" + a + "次数据!!");
            if ("".equals(json) || json == null) {
                return;
            }
            if ("".equals(prefix)) {
                String val[] = json.split("\\*");
                if (val[val.length - 1] != "" && val[val.length - 1] != null && !((val[val.length - 1].startsWith("{") && val[val.length - 1].endsWith("}")) || (val[val.length - 1].startsWith("[") && val[val.length - 1].endsWith("]")))) {
                    prefix = val[val.length - 1];
                    for (int i = 0; i < val.length - 1; i++) {
                        String arr = val[i];
                        if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                            System.out.println("接收数据:" + arr);
                        } else {

                            System.out.println("错误数据丢掉1:" + arr);
                        }
                    }
                } else {
                    for (String arr : val) {
                        if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                            //第一个数据完整
                            System.out.println("接收数据:" + arr);
                        } else {
                            System.out.println("错误数据丢掉2:" + arr);
                        }
                    }

                }

            } else {
                String value = prefix + json;
                String oldPrefix = prefix;
                prefix = "";

                String val[] = value.split("\\*");
                if (val[val.length - 1] != "" && val[val.length - 1] != null && !((val[val.length - 1].startsWith("{") && val[val.length - 1].endsWith("}")) || (val[val.length - 1].startsWith("[") && val[val.length - 1].endsWith("]")))) {
                    prefix = val[val.length - 1];
                    for (int i = 0; i < val.length - 1; i++) {
                        String arr = val[i];
                        if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                            try {
                                JSONObject.parseObject(arr);
                                System.out.println("接收数据:" + arr);
                            } catch (Exception e) {
                                arr = arr.substring(oldPrefix.length());
                                if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                                    System.out.println("接收数据:" + arr);
                                    System.out.println("错误数据丢掉3:" + oldPrefix);
                                } else {
                                    System.out.println("错误数据丢掉4:" + oldPrefix + arr);
                                }
                            }

                        } else {
                            try {
                                JSONObject.parseObject(arr);
                                System.out.println("接收数据:" + arr);
                            } catch (Exception e) {
                                arr = arr.substring(oldPrefix.length());
                                if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                                    System.out.println("接收数据:" + arr);
                                    System.out.println("错误数据丢掉10:" + oldPrefix);
                                } else {
                                    System.out.println("错误数据丢掉11:" + oldPrefix + arr);
                                }
                            }
                        }
                    }
                } else {
                    for (String arr : val) {
                        if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                            //第一个数据完整
                            if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                                try {
                                    JSONObject.parseObject(arr);
                                    System.out.println("接收数据:" + arr);
                                } catch (Exception e) {
                                    arr = arr.substring(oldPrefix.length());
                                    if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                                        System.out.println("接收数据:" + arr);
                                        System.out.println("错误数据丢掉6:" + oldPrefix);
                                    } else {
                                        System.out.println("错误数据丢掉7:" + oldPrefix + arr);
                                    }
                                }
                            } else {
                                System.out.println("错误数据丢掉8:" + oldPrefix + arr);
                            }
                        } else {
                            System.out.println("错误数据丢掉9:" + oldPrefix + arr);

                        }
                    }

                }
            }
            a++;
        }
        System.out.println("当前prefix值:" + prefix);
    }

    private static void unpack(String json) {
        if ("".equals(json) || json == null) {
            return;
        }
        if ("".equals(prefix)) {
            String val[] = json.split("\\*");
            if (val[val.length - 1] != "" && val[val.length - 1] != null && !((val[val.length - 1].startsWith("{") && val[val.length - 1].endsWith("}")) || (val[val.length - 1].startsWith("[") && val[val.length - 1].endsWith("]")))) {
                prefix = val[val.length - 1];
                for (int i = 0; i < val.length - 1; i++) {
                    String arr = val[i];
                    if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                        System.out.println("接收数据:" + arr);
                    } else {

                        System.out.println("错误数据丢掉1:" + arr);
                    }
                }
            } else {
                for (String arr : val) {
                    if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                        //第一个数据完整
                        System.out.println("接收数据:" + arr);
                    } else {
                        System.out.println("错误数据丢掉2:" + arr);
                    }
                }

            }

        } else {
            String value = prefix + json;
            String oldPrefix = prefix;
            prefix = "";

            String val[] = value.split("\\*");
            if (val[val.length - 1] != "" && val[val.length - 1] != null && !((val[val.length - 1].startsWith("{") && val[val.length - 1].endsWith("}")) || (val[val.length - 1].startsWith("[") && val[val.length - 1].endsWith("]")))) {
                prefix = val[val.length - 1];
                for (int i = 0; i < val.length - 1; i++) {
                    String arr = val[i];
                    if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                        try {
                            JSONObject.parseObject(arr);
                            System.out.println("接收数据:" + arr);
                        } catch (Exception e) {
                            arr = arr.substring(oldPrefix.length());
                            if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                                System.out.println("接收数据:" + arr);
                                System.out.println("错误数据丢掉3:" + oldPrefix);
                            } else {
                                System.out.println("错误数据丢掉4:" + oldPrefix + arr);
                            }
                        }

                    } else {
                        try {
                            JSONObject.parseObject(arr);
                            System.out.println("接收数据:" + arr);
                        } catch (Exception e) {
                            arr = arr.substring(oldPrefix.length());
                            if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                                System.out.println("接收数据:" + arr);
                                System.out.println("错误数据丢掉10:" + oldPrefix);
                            } else {
                                System.out.println("错误数据丢掉11:" + oldPrefix + arr);
                            }
                        }
                    }
                }
            } else {
                for (String arr : val) {
                    if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                        //第一个数据完整
                        if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                            try {
                                JSONObject.parseObject(arr);
                                System.out.println("接收数据:" + arr);
                            } catch (Exception e) {
                                arr = arr.substring(oldPrefix.length());
                                if ((arr.startsWith("{") && arr.endsWith("}")) || (arr.startsWith("[") && arr.endsWith("]"))) {
                                    System.out.println("接收数据:" + arr);
                                    System.out.println("错误数据丢掉6:" + oldPrefix);
                                } else {
                                    System.out.println("错误数据丢掉7:" + oldPrefix + arr);
                                }
                            }
                        } else {
                            System.out.println("错误数据丢掉8:" + oldPrefix + arr);
                        }
                    } else {
                        System.out.println("错误数据丢掉9:" + oldPrefix + arr);

                    }
                }

            }
        }
        System.out.println("当前prefix值:" + prefix);
    }


}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用Java编写的TCP协议分析代码示例,仅供参考: ```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class ProtocolAnalyzerClient { public static void main(String[] args) throws IOException { String hostName = "localhost"; int portNumber = 12345; try ( Socket socket = new Socket(hostName, portNumber); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); ) { // 发送数据包 String command = "GET"; String arg1 = "/index.html"; String arg2 = "HTTP/1.1"; String data = command + "," + arg1 + "," + arg2 + "\n"; out.write(data.getBytes()); // 接收响应数据包 byte[] buffer = new byte[1024]; int bytesRead = in.read(buffer); if (bytesRead > 0) { String response = new String(buffer, 0, bytesRead); // 解析响应数据包 System.out.println("Response: " + response); } } catch (IOException e) { System.out.println("Exception caught when trying to connect to server " + hostName + " on port " + portNumber); System.out.println(e.getMessage()); } } } ``` 此示例代码假设客户端将每个数据包作为以逗号分隔的字符串发送,并且每个数据包包含三个字段:命令、参数1和参数2。在主函数中,程序创建了一个Socket对象,并将其连接到指定的主机和端口号。然后,程序使用OutputStream来发送数据包,并使用InputStream来接收响应数据包。在发送数据包时,程序将数据包的三个字段作为字符串连接并写入OutputStream。在接收响应数据包时,程序读取InputStream中的字节,并将其转换为字符串。然后,程序解析响应数据包中的数据,并将其打印到控制台上。 当然,这只是一个简单的示例,实际的TCP协议分析器需要更多的代码来处理复杂的数据包、错误处理等问题。但是,这个示例可以帮助您了解如何使用Java编写TCP协议分析代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值