python + vue 实现websocket

python

import asyncio
import datetime
import random
import websockets

print(' ========= websocket is going to run =========')


async def time(websocket, path):
    while True:
        now = str(random.randint(0,100))
        print(now)
        await websocket.send(now)
        await asyncio.sleep(random.random() * 3)


start_server = websockets.serve(time, "10.200.125.3", 80)
print(' ========= websocket running =========')
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


vue

<template>
    <div>
        <span>test</span>
        <el-progress :text-inside="true" :stroke-width="26" :percentage="Number(textArea_test)"></el-progress>
    </div>
</template>

<script>
export default {
data() {
    return {
        websock: null,
        textArea_test:'',
        count_t:0
    }
},
 methods: {

    runSocket() {
    //   let count_rev = 0;
      this.ws = new WebSocket("ws://10.200.125.3/");
      this.ws.onopen = this.websocketonopen;
      this.ws.onerror = this.websocketonerror;
      this.ws.onmessage = this.websocketonmessage;
      this.ws.onclose = this.websocketclose;
    },
 
    // 定义 websocket open属性的函数
    websocketonopen: function () {
      console.log('WebSocket连接成功');
    },
    // 定义 websocket onerror属性的函数
    websocketonerror: function (e) {
      console.log('WebSocket连接发生错误');
      console.log(e)
    },
    // 定义 websocket onmessage属性的函数
    websocketonmessage: function (e) {
      this.count_t = this.count_t + 1;
      console.log(this.count_t);   //打印接收到了多少次服务端的消息
      this.textArea_test = e.data;  //改变界面上某个控件的展示内容
    },
    // 定义 websocket onclose属性的函数
    websocketclose: function (e) {
      console.log('connection closed');
      console.log(e)
    },
 
    openTest() {
      this.runSocket();
    }
},
created(){
    this.openTest()
}


}
 </script>

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值