Python Websockets使用,实现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())

以下是客户端 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())

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>

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值