Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Websocket Server 在对接 python3 ws client时 pong 无效导致断联 #685

Open
Philogag opened this issue Feb 18, 2025 · 1 comment
Open

Comments

@Philogag
Copy link

BUG详情

当前 Websocket Server 在接收到客户端 Ping 时固定返回空的 Pong
然而 Python3 标准库 websockets 在处理返回的 Pong 包时要求 Pong 包携带 Ping 包的 payload

https://github.com/python-websockets/websockets/blob/7ac73c645329055a3c352077b8055e6ed65fa46c/src/websockets/legacy/protocol.py#L838C1-L850C43

https://github.com/python-websockets/websockets/blob/7ac73c645329055a3c352077b8055e6ed65fa46c/src/websockets/legacy/protocol.py#L1118C1-L1136C48

导致客户端将会主动断开连接

修复方法

Pong 包将接收到的 Ping 包的 msg 携带即可

diff -uparN libhv-1.2.6/http/WebSocketChannel.h libhv-1.2.6-new/http/WebSocketChannel.h
--- libhv-1.2.6/http/WebSocketChannel.h	2022-06-27 01:09:08.000000000 +0800
+++ libhv-1.2.6-new/http/WebSocketChannel.h	2025-02-18 11:58:25.083446807 +0800
@@ -75,12 +75,19 @@ public:
         return write(WS_SERVER_PING_FRAME, WS_SERVER_MIN_FRAME_SIZE);
     }
 
-    int sendPong() {
+    int sendPong(const std::string& msg = "") {
         std::lock_guard<std::mutex> locker(mutex_);
         if (type == WS_CLIENT) {
             return write(WS_CLIENT_PONG_FRAME, WS_CLIENT_MIN_FRAME_SIZE);
+        } else {
+            int frame_size = ws_calc_frame_size(msg.size(), 0);
+            if (sendbuf_.len < frame_size) {
+                sendbuf_.resize(ceil2e(frame_size));
+            }
+            ws_build_frame(sendbuf_.base, msg.c_str(), msg.size(), 0, 0, WS_OPCODE_PONG, 1);
+            printf("[%s:%d] send pong len=%d\n", __func__, __LINE__, frame_size);
+            return write(sendbuf_.base, frame_size);
         }
-        return write(WS_SERVER_PONG_FRAME, WS_SERVER_MIN_FRAME_SIZE);
     }
 
 protected:
diff -uparN libhv-1.2.6/http/server/HttpHandler.cpp libhv-1.2.6-new/http/server/HttpHandler.cpp
--- libhv-1.2.6/http/server/HttpHandler.cpp	2022-06-27 01:09:08.000000000 +0800
+++ libhv-1.2.6-new/http/server/HttpHandler.cpp	2025-02-18 11:53:50.853566023 +0800
@@ -91,7 +91,7 @@ bool HttpHandler::SwitchWebSocket(hio_t*
         case WS_OPCODE_PING:
             // printf("recv ping\n");
             // printf("send pong\n");
-            ws_channel->sendPong();
+            ws_channel->sendPong(msg);
             break;
         case WS_OPCODE_PONG:
             // printf("recv pong\n");
@ithewei
Copy link
Owner

ithewei commented Feb 18, 2025

这个在v1.3.2版本修复过的,见6f9d7c8

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants