python后端和前端通过websocket通讯发消息最小案例,十分钟看懂

前端和后端通过websocket实现发送消息案例,用于理解websocket,服务端可以主动给客户端发送消息,而且是长连接,比http效率高,因为http要不断地创建和销毁socket实例,导致压力很大。websocket一次创建,长久链接。

python的websocket服务端:

#!/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和js客户端:

<!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>

效果演示:

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/133040897