推荐使用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服务和客户端请求