websocket使用

websocket的使用主要就是初始化一个websocket实例,定义连接路径即请求后端的接口路径,之后就是绑定该websocket的onopen,onerror,onmessage,onsend,onclose方法。
onopen:连接成功之后执行的方法;
onerror:错误异常时执行方法;
onmessage:接收到后端推送的消息时执行的方法
onsend:前端向后端发送消息时执行的方法;
onclose:连接关闭时执行的方法。

 created() {
    this.initWebSocket()
  },
  watch:{
	  // 监听消息数组变化,
	  messageList: {
	      handler(newValue, oldValue) {
	        if (newValue !== oldValue) {
	          this.messageList = newValue
	        }
	      },
	      deep: true,
	      immediate: true,
	    },
	},
	methods:{
	    // 消息推送
	    initWebSocket() {
	      // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
	      var userId = this.$store.getters.userInfo.id
	      var url =
	        window._CONFIG['domianURL'].replace('https://', 'ws://').replace('http://', 'ws://') + '/websocket/' + userId
	      this.websock = new WebSocket(url)
	      this.websock.onopen = this.websocketonopen
	      this.websock.onerror = this.websocketonerror
	      this.websock.onmessage = this.websocketonmessage
	      this.websock.onclose = this.websocketclose
	    },
	    websocketonopen() {
	      console.log('WebSocket连接成功')
	    },
	    websocketonerror(e) {
	      console.log('WebSocket连接发生错误')
	    },
	    // 接受后端返来的最新消息,并进行数据处理,推送到消息最前面
	    websocketonmessage(e) {
	      let that = this
	      let res = JSON.parse(e.data)
	      let data = {
	        createTime: res.date,
	        message: res.msgTxt,
	        id: res.msgId,
	      }
	      that.messageList.unshift(data)
	    },
	    websocketclose(e) {
	      console.log('connection closed (' + e.code + ')')
	    },
	}

参考文章:

https://blog.csdn.net/qq_63312957/article/details/125375122
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐