Solving the problem of SOCKET/serial communication sticky packets, with detailed code

Packet sticking problems may occur in UDP TCP or serial communication. Specific solutions include the following
: 1. Customize the package body format to include the header + package body length
2. Increase the read buffer buffer

This article introduces the first method of
socket communication. We usually start a thread and read the information in an infinite loop.

We have determined the protocol format as follows: hexadecimal representation
A3A4 + length of two bytes + json
, where A3A4 is the protocol header and json is the specific data we need.

We can always read 4 bytes first to get the complete packet length and then continue reading.

                   byte[] temBuffer = new byte[4];
                    if (mInputStream == null) {
    
    
                        continue;
                    }
                    int ret = mInputStream.read(temBuffer);
                    if (ret > 0) {
    
    
                        byte[] msg = null;
                        //收到一条新命令为0XA3 0XA4开头的
                        if (temBuffer[0] == (byte) 0xA3 && temBuffer[1] == (byte) 0xA4) {
    
    
                            //计算命令长度 即2 3字节组合成Int
                            int cmdSize = ConvertUtilsPlus.getIntFromBytes(temBuffer[2], temBuffer[3]);
                            int bodyLength = 4+ cmdSize;//计算出中长度
                            msg = new byte[bodyLength];//申明本次接收一个完整数据需要的容量
                            int recLength = ret;//记录当前已接收数据的长度
                            int errorCount = 0;//记录错误次数
                            System.arraycopy(temBuffer, 0, msg, 0, recLength);//第一包无脑丢进数组中
                            //如果本次读取到的数据小于总长度那么继续read
                            while (recLength < bodyLength && errorCount < 10) {
    
    
                                byte[] temp = new byte[bodyLength - recLength];
                                int rec = mInputStream.read(temp);
                                if (rec <= 0) {
    
    
                                    errorCount++;
                                    continue;
                                }
                                //复制读取的数据到数组中
                                System.arraycopy(temp, 0, msg, recLength, rec);
                                recLength += rec;
                            }
                        }
                        //没有新消息继续循环
                        if (msg == null) continue;

The getIntFromBytes method is as follows

  public static int getIntFromBytes(byte low_h, byte low_l) {
    
    
        return  (low_h & 0xff) << 8 | low_l & 0xff;
    }

You should have a thorough understanding of the above method if you read the comments.

Guess you like

Origin blog.csdn.net/qq910689331/article/details/107733632