一、后端间通信

server.py

import asyncio
import websockets
import time
 


""" 每隔2s给客户端发送一条消息 """
async def echo(websocket, path):
    while True:
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
        await websocket.send(now) 
        await asyncio.sleep(2)
 

if __name__ == '__main__':
    start_server = websockets.serve(echo,'127.0.0.1',5000) # 改为你自己的地址
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

 

client.py

import asyncio
import websockets
 
 
async def hello(uri):
    async with websockets.connect(uri) as websocket:
        while True:
            recv_text = await websocket.recv()  # 接收消息
            print(recv_text)
         
 
if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(
        hello('ws://127.0.0.1:5000')) # 改为你自己的地址
  1. pip安装websockets
  2. 先启动server.py,再启动client.py
  3. 效果:

img

 

 

二、后端与前端通信

server.py 不变;client使用html页面。

 

2.1 基础版:前端实时获取数据,并堆叠式输出

client.html

<!DOCTYPE html>
<html>
    <head>
        <title>WebSocket demo</title>
    </head>
    <body>
        <script>
            var ws = new WebSocket("ws://127.0.0.1:5000/"),
                messages = document.createElement('ul');
            ws.onmessage = function (event) {
                var messages = document.getElementsByTagName('ul')[0],
                    message = document.createElement('li'),
                    content = document.createTextNode(event.data);
                message.appendChild(content);
                messages.appendChild(message);
            };
            document.body.appendChild(messages);
        </script>
    </body>
</html>

启动server.py后再点开页面,效果:

img

 

2.2 扩展版:前端某组件实时获取数据,并更新值

client.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>页面</title>
</head>
<body>

    <!-- 这两种标签都可以用 -->
    <label id="my_label"></label>
    <div id="my_label" ></div>
    


    <script>
        var websocket = new WebSocket("ws://10.192.87.104:5678/");

        //连接成功建立的回调方法
        websocket.onopen = function () {
            window.alert('连接成功')
        };

        // 前端接收后端传来的消息
        websocket.onmessage = function (event) {
            document.getElementById('my_label').innerText = event.data;
        };

        //连接关闭的回调方法
        websocket.onclose = function () {
            window.alert('连接已断开或未连接')

        };

        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        };

        //关闭连接
        function closeWebSocket() {
            websocket.close();
            window.clearInterval(intervalId);
        }
    </script>
</body>
</html>

启动server.py后再点开页面,效果:标签位置实时更新server传来的值。当然,如果任务需要,也可以实时更新图片

 

参考: https://websockets.readthedocs.io/en/stable/intro.html

 

 

 


Solryu
18 声望5 粉丝