The smallest case of sending messages between python backend and frontend through websocket communication, which can be understood in ten minutes

The front-end and back-end realize the case of sending messages through websocket, which is used to understand websocket. The server can actively send messages to the client, and it is a long connection, which is more efficient than http, because http needs to continuously create and destroy socket instances, resulting in a lot of pressure. big. The websocket is created once and has a long-term connection.

python websocket server:

#!/usr/bin/env python

import asyncio
import websockets


async def echo(websocket):
    while True:
        name = await websocket.recv()
        print(f"接收到消息:{name}")
        replay = f"Hello {name}"
        await websocket.send(replay)
        print(f"发送消息结束,再给他发一个消息")
        await websocket.send("服务端主动给你发消息了")


async def main():
    async with websockets.serve(echo, "localhost", 8765):
        print("服务端启动成功:ws://localhost:8765")
        await asyncio.Future()  # run forever


asyncio.run(main())

html and js client:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script>
            var planWebsocket = null
            var planIP = '127.0.0.1' // IP地址
            var planPort = '8765' // 端口号
            function initWebpack() {
                //初始化websocket
                if ('WebSocket' in window) {
                    planWebsocket = new WebSocket(
                        'ws://' + planIP + ':' + planPort
                    ) // 通信地址
                    planWebsocket.onopen = function (event) {
                        console.log('建立连接')
                        let sendData = '你好啊'
                        planWebsocket.send(sendData) // 发送获取数据的接口
                    }

                    planWebsocket.onmessage = function (event) {
                        console.log('收到消息:' + event.data)
                        document.getElementById("receive").innerText = event.data
                    }

                    planWebsocket.onclose = function (event) {
                        console.log('连接关闭')
                    }

                    planWebsocket.onerror = function () {
                        alert('websocket通信发生错误!')
                    }
                } else {
                    alert('该浏览器不支持websocket!')
                }
            }

            initWebpack() //调用
        </script>
    </head>
    <body>
        <div>websocker测试</div>
        <div>
            <div>接收到的服务端的消息:</div>
            <div id="receive"></div>
        </div>
    </body>
</html>

Effect demonstration:

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/133040897