3.WebSocket的应用和实现

WebSocket的应用和实现

1. 什么是WebSocket

WebSocket 是 HTML5 中的协议,支持持久连接,http协议不支持持久性连接。

2. WebSocket 是什么样的协议,具有什么优点

HTTP 的声明周期通过Request来界定,也就是一个Request一个Response,而且Response是被动的,不能主动发起。

WebSocket 是基于HTTP协议的,借用了Http协议来完成一部分握手,在握手阶段与HTTP是相同的。

3. vue中WebSocket

 initWebSocket () {
     // 获取WebSocket连接信息
     this.$api('systemManage', {}).then(res => {
     if (res.code != 0) return
     let socketWs = res.data.socketWs
     let socketWss = res.data.socketWss
     let wsuri = ''
     let ishttps = document.location.protocol == 'https:'
     if (ishttps) {
     wsuri = 'wss:' + socketWss// wss地址
     } else {
     wsuri = 'ws:' + socketWs// ws地址
     }
     // console.log(wsuri)
     this.websock = new WebSocket(wsuri)
     this.websock.onopen = this.websocketonopen
     this.websock.onerror = this.websocketonerror
     this.websock.onmessage = this.websocketonmessage
     this.websock.onclose = this.websocketclose
     }).catch(err => {
     this.$Message.error(err.message)
     })
 },
 
   websocketonopen () {
      // console.log('WebSocket连接成功' + '状态码' + this.websock.readyState)
      this.websocketsend('userJoin&chronic&' + this.userInfo.token)
    },
    websocketonerror (e) { // 错误
      // console.log('WebSocket连接发生错误')
    },
    websocketonmessage (e) { // 数据接收
      // console.log('接收数据:' + e.data)
      this.websockTimeMersure++
    },
    websocketsend (agentData) { // 数据发送
      // console.log('数据发送' + agentData)
      this.websock.send(agentData)
    },
    websocketclose () { // 关闭
      // console.log('websocket关闭')
      // this.websocketsend('userLeave&chronic&' + this.userInfo.token)
    },
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值