美文网首页
长连接在vue项目中的应用

长连接在vue项目中的应用

作者: meng_281e | 来源:发表于2019-12-21 15:02 被阅读0次
常见的适用业务场景:

1.实时更新的统计图表;
2.叫号系统(餐饮叫号、银行叫号、医院排队叫号等)
3.读卡(读就诊卡、身份证等)
4.聊天系统
....
需要实时与后端进行实时通信的

什么是长连接、短连接

<短链接> 客户端和服务器每进行一次HTTP操作,就建立一次连接,任务结束就中断连接。

<长连接> 浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。 ws.png

#######WebSocket事件/方法
事件

open    Socket.onopen       连接建立时触发
message Socket.onmessage    客户端接收服务端数据时触发
error   Socket.onerror      通信发生错误时触发
close   Socket.onclose      连接关闭时触发

方法

Socket.send()   使用连接发送数据
Socket.close()   关闭连接
用在vue中
<template>
    <div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                websock: null,
            }
        },
    created(){
           //页面刚进入时开启长连接
            this.initWebSocket()
       },
    destroyed: function() {
    //页面销毁时关闭长连接
      this.websocketclose();
    },
    methods: { 
      initWebSocket(){ //初始化weosocket 
        const wsuri = process.env.WS_API + "ws地址";
        this.websock = new WebSocket(wsuri); 
        this.websocket.onopen = this.websocketonopen;
        this.websocket.onerror = this.websocketonerror;
        this.websock.onmessage = this.websocketonmessage; 
        this.websock.onclose = this.websocketclose;
       }, 

      websocketonopen() {
        console.log("WebSocket连接成功");
      },
      websocketonerror(e) { //错误
        console.log("WebSocket连接发生错误");
      },
      websocketonmessage(e){ //数据接收 
        const redata = JSON.parse(e.data);
        console.log(redata.value); 
      }, 

      websocketsend(agentData){//数据发送 
        this.websock.send(agentData); 
      }, 

      websocketclose(e){ //关闭 
        console.log("connection closed (" + e.code + ")"); 
     },
   }, 
  }
 </script>

相关文章

网友评论

      本文标题:长连接在vue项目中的应用

      本文链接:https://www.haomeiwen.com/subject/ugrgnctx.html