socketify websocket 简单试用

内容来自官方示例,主要是体验下webssocket的发布订阅能力

参考代码

  • app.py
from socketify import App, CompressOptions


def ws_open(ws):
    print("A WebSocket got connected!")
    # Let this client listen to topic "broadcast"
    ws.subscribe("broadcast")


def ws_message(ws, message, opcode):
    # Broadcast this message
    ws.publish("broadcast", message, opcode)

app = App()
app.ws(
    "/wsapp",
    {
        "compression": CompressOptions.SHARED_COMPRESSOR,
        "max_payload_length": 16 * 1024 * 1024,
        "idle_timeout": 60,
        "open": ws_open,
        "message": ws_message,
        # The library guarantees proper unsubscription at close
        "close": lambda ws, code, message: print("WebSocket closed"),
        "subscription": lambda ws, topic, subscriptions, subscriptions_before: print(f'subscription/unsubscription on topic {topic} {subscriptions} {subscriptions_before}'),
    },
)
app.static("/static", "./static")
app.any("/", lambda res, req: res.end("Nothing to see here!"))
app.listen(
    3000,
    lambda config: print("Listening on port http://localhost:%d now\n" % (config.port)),
)
app.run()
  • index.html

静态页面方便测试的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ws test</title>
</head>
<body>
    
    <script>
        const ws = new WebSocket('ws://localhost:3000/wsapp');
        ws.onopen = () => {
            console.log('connected');
            ws.send('Hello Server');
        };
        ws.onmessage = (message) => {
            console.log('received:', message.data);
        };

        ws.onerror = (error) => {
            console.log('error:', error);
        };
    </script>
    <button onclick="ws.send('Hello Server dddddddd')">Send</button>
</body>
</html>
  • 效果

 

说明

从体验上来看是可以支持类似发布订阅的能力,但是功能上并不是特别稳定(可能是用法不对?),同时注意安装的时候依赖libuv

参考资料

https://github.com/cirospaciari/socketify.py

https://docs.socketify.dev/getting-started.html

posted on 2025-04-15 08:00  荣锋亮  阅读(27)  评论(0)    收藏  举报

导航