繁体   English   中英

初始握手后,如何在 Python WebSockets 服务器中将消息从服务器发送到客户端?

[英]How to send messages from server to client in a Python WebSockets server, AFTER initial handshake?

这是一个小型的 websockets 客户端和服务器 POC。 它将单个硬编码消息字符串从 (Python) 服务器发送到 Javascript 客户端页面。

问题是,如何进一步发送临时消息? 从服务器到客户端。

带有嵌入式 Javascript 的微型 HTML 客户端页面:

<!DOCTYPE html> 
<html lang="en">
<body> See console for messages </body>
<script>
# Create websocket
const socket = new WebSocket('ws://localhost:8000');

# Add listener to receive server messages
socket.addEventListener('open', function (event) {
    socket.send('Connection Established');
});

# Add message to browser console
socket.addEventListener('message', function (event) { 
    console.log(event.data);
});
 
</script>
</html>

这是 Python 服务器代码:

import asyncio 
import websockets
import time 

# Create handler for each connection
async def handler(websocket, path):
    await websocket.send("message from websockets server")

# Start websocket server
start_server = websockets.serve(handler, "localhost", 8000)

# Start async code
asyncio.get_event_loop().run_until_complete(start_server) 
asyncio.get_event_loop().run_forever()

这成功地将硬编码消息从服务器发送到客户端。 您可以在浏览器控制台中看到该消息。 此时websocket打开。

主应用程序(未显示)现在需要发送消息。 这些将是动态消息,而不是硬编码。

我们如何从服务器发送稍后的动态消息? 这里的代码运行

我想将套接字放入全局变量并调用发送方法,但这是不可能的,因为服务器运行连续循环。

您可以像这样在 Python 服务器代码中插入更多消息:


import asyncio
import datetime
from typing import Iterator
import websockets
import random

websocket_connections = set()
sock_port = 8000
sock_url = 'localhost'
global_socket = lambda: None

async def register(websocket):
    print('register event received')
    websocket_connections.add(websocket) # Add this client's socket
    global_socket = websocket

async def poll_log():
    await asyncio.sleep(0.3) # Settle
    while True:
        await asyncio.sleep(0.3) # Slow things down
        
        # Send a dynamic message to the client after random delay
        r = random.randint(1, 10)
        if (r == 5): # Only send 10% of the time
            a_msg = "srv -> cli: " + str(random.randint(1,10000))
            print("sending msg: " + a_msg)
            websockets.broadcast(websocket_connections, a_msg) # Send to all connected clients
        
async def main():
    sock_server = websockets.serve(register, sock_url, sock_port)
    await asyncio.sleep(0.3) # Start up time
    async with sock_server: await poll_log()

if __name__ == "__main__":
    print("Websockets server starting up ...")
    asyncio.run(main())

这里有一个非常有用的完整的全双工 Websockets 应用程序示例。 该示例是 Websockets 10.4 文档的一部分。 作为参考和了解如何使用 websockets 非常有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM