vue+koa+python websocket通信

需求: python制作的工具拿到语音识别结果,发送给koa后端,然后在vue前端显示出来,由于要实时显示,所以需要进行vue+koa+python websocket通信

在这里插入图片描述
在这里插入图片描述
很明显python,vue都是websocket客户端,koa作为websocket服务器端。

一、python websocket

只用将websocket发送给服务器

1.安装websocket

pip install websocket-client 

2.与服务器建立websocket连接,发送消息

# 是否在控制台打印连接和消息发送接受情况
websocket.enableTrace(False)      
# 与服务器端建立的websocket连接
# url上传递中文参数要进行编码,通过会议室名区分不同的连接
url = SERVER_WS_URL + "?name=" + urllib.parse.quote(self.combo.currentText())
self.websocket_server = websocket.WebSocketApp(url,on_open=server_on_open,on_message=server_on_message,on_close=server_on_close)
# 开启长连接
_thread.start_new_thread(self.websocket_server.run_forever, ())
# 将消息发送服务器端
main.websocket_server.send(ws.finalResult)

def server_on_open(ws):
    pass


def server_on_message(ws, message):
    pass


def server_on_close(ws):
    pass

二、vue websocket

vue中使用websocket不用额外安装websocket的包,因为HTML5中已经有了websocket API,所以也可以说是HTML5 webscoket

只用接受服务器发送的websocket信息

//WebSocket连接地址
const websocketUrl = 'ws://172.25.78.33:3000/ws'

export function getWebSocket(name) {
    console.log(websocketUrl + "?name=" + name)
    return new WebSocket(websocketUrl + "?name=" + name)
}

socket = getWebSocket(this.room.name);
            socket.onopen = function () {};
            socket.onmessage = function (msg) {
              const result = JSON.parse(msg.data);
              if (result.data != null) {
                //onmessage       
              } else {
                //open or close
              }
            };
            socket.onclose = function () {};
            socket.onerror = function () {};

三、koa websocket

服务器既要接收来自python客户端的信息又要将它发送给vue

  1. 安装websocket
npm install koa-websocket 
const websockify = require('koa-websocket');

let rooms = {
  'TV会议室1': [],
  'TV会议室2': [],
  'TV会议室3': [],
  '西区会议室1': [],
  '西区会议室2': [],
  '西区会议室3': [],
  '东区会议室': [],
  '西区培训室': [],
  '东区培训室': []
}
//等同于websocket onOpen
app.ws.use(function (ctx, next) {
  //通过push ctx区分不同的会议室
  rooms[ctx.query.name].push(ctx)
  return next(ctx)
})

app.ws.use(route.all('/ws', (ctx) => {
  ctx.websocket.on('message', function (result) {
  })
  ctx.websocket.on('close', function () {
  })
}));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Selenium399

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值