当前位置:   article > 正文

Python Websockets使用,实现Vue通信_python使用websocket与vue前端实现通讯

python使用websocket与vue前端实现通讯

推荐使用python3.6以上版本来运行websockets

pip install websockets

websockets 是一个用于在 Python 中构建 WebSocket 服务器和客户端的库,专注于正确性、简单性、健壮性和性能。
它建立在 Python 的标准异步 I/O 框架 asyncio 之上,提供了一个优雅的基于协程的 API。

以下是服务端 server.py代码:

import asyncio     # 异步I/O
import websockets

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message);

async def main():
    async with websockets.serve(echo, "localhost", 8765):
        await asyncio.Future();

asyncio.run(main())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

以下是客户端 client.py代码:

import asyncio
import websockets

async def hello():
    async with websockets.connect("ws://localhost:8765") as websocket:
        await websocket.send("Hello world!")
        await websocket.recv()

asyncio.run(hello())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

websockets官网:websockets

前端(Vue)通信

以下是client.vue代码:

<template>
    <div>
        <input type="text" v-model="val">
        <button type="button" @click="send">推送</button>
    </div>
</template>

<script>
export default {
    name: "IDE",
    data() {
        return {
            ws: null,
            val:""
        }
    },
    mounted() {
        let $this = this;
        if(typeof WebSocket === 'undefined')
            return console.log('您的浏览器不支持websocket')
        $this.ws = new WebSocket("ws://localhost:8765")
        $this.ws.onopen = () => {
            // 连接建立之后执行
            console.log("已连接")
        }
        
        $this.ws.onmessage = (msg) => {
            // 数据接收
            console.log(msg)
        }
        
        $this.ws.onerror = ()=>{
            // 连接建立失败重连
        }

        $this.ws.onclose= ()=>{
            // 连接关闭时执行
        }
    },
    methods: {
        send() {
            this.ws.send(this.val)
        }
    },
    destroyed(){
        //离开路由后断开websocket连接
        this.ws.close();
    }
}
</script>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

运行效果:
运行效果
参考文档:
vue中如何使用websocket
Python的websockets库
使用Python创建websocket服务和客户端请求

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/66573
推荐阅读
相关标签
  

闽ICP备14008679号