Explorar el Código

fix[backend]: 修复"帧头和长度"获取帧数据的逻辑

tribf hace 4 años
padre
commit
b0dd6f74fb
Se han modificado 1 ficheros con 18 adiciones y 10 borrados
  1. 18 10
      static/server/app.js

+ 18 - 10
static/server/app.js

@@ -112,6 +112,8 @@ io.sockets.on('connection', function (socket) {
112 112
 
113 113
 })
114 114
 
115
+const frame_header_and_size_bytes = 1 + 2;
116
+
115 117
 socketServer.on('connection',(socket)=>{
116 118
     console.log('连接已建立')
117 119
     socketEvent = socket
@@ -128,19 +130,27 @@ socketServer.on('connection',(socket)=>{
128 130
         if (lastBuffer !== null) {
129 131
             data = Buffer.concat([lastBuffer, data]);
130 132
         }
133
+
131 134
         let flag = 1;
132 135
         while(flag){
133
-            let validNumByteArray = new Uint8Array(data.slice(1, 3));
134
-            let validNum = validNumByteArray[0]
135
-            if(data.length >validNum) {
136
-                let validateData = data.slice(0, 1 + 2 +validNum);
137
-                setAllCommand(validateData)
138
-                lastBuffer = data.slice(1+2+validNum)
139
-                if(lastBuffer.length >=1+2+validNum) {
136
+            if (data.length < frame_header_and_size_bytes) {
137
+                lastBuffer = data;
138
+                break;
139
+            }
140
+
141
+            let dataLength = data.readUIntLE(1, 2)
142
+            let frameLength = frame_header_and_size_bytes + dataLength
143
+
144
+            if(data.length > frameLength) {
145
+                let frame = data.slice(0, frameLength);
146
+                setAllCommand(frame)
147
+                lastBuffer = data.slice(frameLength)
148
+
149
+                if(lastBuffer.length >= frame_header_and_size_bytes) {
140 150
                     data = lastBuffer
141 151
                     continue;
142 152
                 }
143
-            } else if(data.length == 1+2+validNum) {
153
+            } else if(data.length === frameLength) {
144 154
                 setAllCommand(data)
145 155
                 lastBuffer = null;
146 156
             } else {
@@ -148,7 +158,6 @@ socketServer.on('connection',(socket)=>{
148 158
             }
149 159
             flag = 0;
150 160
         }
151
-        // 处理压力板发过来的数据
152 161
     });
153 162
     socket.on('error', (err)=>{
154 163
         console.warn(err);
@@ -156,7 +165,6 @@ socketServer.on('connection',(socket)=>{
156 165
     });
157 166
     socket.on('end', ()=>{
158 167
         io.sockets.emit('disConnectOneClient');
159
-        //socketServer.close();
160 168
     });
161 169
 })
162 170