瀏覽代碼

websocket fragment if send len > 65535

ithewei 4 年之前
父節點
當前提交
986ebb8b11
共有 1 個文件被更改,包括 25 次插入16 次删除
  1. 25 16
      http/WebSocketChannel.h

+ 25 - 16
http/WebSocketChannel.h

@@ -26,19 +26,11 @@ public:
     }
 
     int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true) {
-        bool has_mask = false;
-        char mask[4] = {0};
-        if (type == WS_CLIENT) {
-            has_mask = true;
-            *(int*)mask = rand();
-        }
-        int frame_size = ws_calc_frame_size(len, has_mask);
-        std::lock_guard<std::mutex> locker(mutex_);
-        if (sendbuf_.len < frame_size) {
-            sendbuf_.resize(ceil2e(frame_size));
+        int fragment = 0xFFFF; // 65535
+        if (len > fragment) {
+            return send(buf, len, fragment, opcode);
         }
-        ws_build_frame(sendbuf_.base, buf, len, mask, has_mask, opcode, fin);
-        return write(sendbuf_.base, frame_size);
+        return send_(buf, len, opcode, fin);
     }
 
     // websocket fragment
@@ -48,29 +40,46 @@ public:
     // send(p, remain, WS_OPCODE_CONTINUE, true)
     int send(const char* buf, int len, int fragment, enum ws_opcode opcode = WS_OPCODE_BINARY) {
         if (len <= fragment) {
-            return send(buf, len, opcode, true);
+            return send_(buf, len, opcode, true);
         }
 
         // first fragment
-        int nsend = send(buf, fragment, opcode, false);
+        int nsend = send_(buf, fragment, opcode, false);
         if (nsend < 0) return nsend;
 
         const char* p = buf + fragment;
         int remain = len - fragment;
         while (remain > fragment) {
-            nsend = send(p, fragment, WS_OPCODE_CONTINUE, false);
+            nsend = send_(p, fragment, WS_OPCODE_CONTINUE, false);
             if (nsend < 0) return nsend;
             p += fragment;
             remain -= fragment;
         }
 
         // last fragment
-        nsend = send(p, remain, WS_OPCODE_CONTINUE, true);
+        nsend = send_(p, remain, WS_OPCODE_CONTINUE, true);
         if (nsend < 0) return nsend;
 
         return len;
     }
 
+protected:
+    int send_(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true) {
+        bool has_mask = false;
+        char mask[4] = {0};
+        if (type == WS_CLIENT) {
+            has_mask = true;
+            *(int*)mask = rand();
+        }
+        int frame_size = ws_calc_frame_size(len, has_mask);
+        std::lock_guard<std::mutex> locker(mutex_);
+        if (sendbuf_.len < frame_size) {
+            sendbuf_.resize(ceil2e(frame_size));
+        }
+        ws_build_frame(sendbuf_.base, buf, len, mask, has_mask, opcode, fin);
+        return write(sendbuf_.base, frame_size);
+    }
+
 private:
     Buffer      sendbuf_;
     std::mutex  mutex_;