Parcourir la source

test: python websockets

ithewei il y a 2 ans
Parent
commit
6f9d7c8d25

+ 4 - 0
examples/websocket_client_test.cpp

@@ -5,6 +5,7 @@
  * @server  bin/websocket_server_test 8888
  * @client  bin/websocket_client_test ws://127.0.0.1:8888/test
  * @clients bin/websocket_client_test ws://127.0.0.1:8888/test 100
+ * @python  scripts/websocket_server.py
  * @js      html/websocket_client.html
  *
  */
@@ -33,6 +34,9 @@ public:
             printf("onclose\n");
         };
 
+        // ping
+        setPingInterval(10000);
+
         // reconnect: 1,2,4,8,10,10,10...
         reconn_setting_t reconn;
         reconn_setting_init(&reconn);

+ 2 - 0
examples/websocket_server_test.cpp

@@ -4,6 +4,7 @@
  * @build   make examples
  * @server  bin/websocket_server_test 9999
  * @client  bin/websocket_client_test ws://127.0.0.1:9999/
+ * @python  scripts/websocket_server.py
  * @js      html/websocket_client.html
  *
  */
@@ -61,6 +62,7 @@ int main(int argc, char** argv) {
     });
 
     WebSocketService ws;
+    // ws.setPingInterval(10000);
     ws.onopen = [](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) {
         printf("onopen: GET %s\n", req->Path().c_str());
         auto ctx = channel->newContextPtr<MyContext>();

+ 1 - 1
http/client/WebSocketClient.cpp

@@ -149,7 +149,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
                     {
                         // printf("recv ping\n");
                         // printf("send pong\n");
-                        channel->sendPong();
+                        channel->send(msg, WS_OPCODE_PONG);
                         break;
                     }
                     case WS_OPCODE_PONG:

+ 1 - 1
http/server/HttpHandler.cpp

@@ -175,7 +175,7 @@ bool HttpHandler::SwitchWebSocket() {
         case WS_OPCODE_PING:
             // printf("recv ping\n");
             // printf("send pong\n");
-            ws_channel->sendPong();
+            ws_channel->send(msg, WS_OPCODE_PONG);
             break;
         case WS_OPCODE_PONG:
             // printf("recv pong\n");

+ 18 - 0
scripts/websocket_server.py

@@ -0,0 +1,18 @@
+#!/usr/bin/env python3
+
+# pip3 install websockets
+
+import asyncio
+import websockets
+
+async def echo(websocket):
+    async for message in websocket:
+        print(message)
+        await websocket.send(message)
+
+async def serve(port):
+    async with websockets.serve(echo, "0.0.0.0", port):
+        await asyncio.Future()
+
+if __name__ == "__main__":
+    asyncio.run(serve(9999))