vue-websocket的使用

问题描述

在vue前端项目开发过程中需要实时显示部分数据,在通过多个处理方式中选择使用websocket来解决这个问题。

解决方案

vue单页代码
export default {
	// 关闭页面时断开socket连接
	beforeDestroy () { 
	    this.websocketclose()
	},
	methods: {
		// 初始化websocket
	    initWebsocket () {
		  // getUrl()访问服务器获取ip地址方法
	      getUrl().then(res => {
	      	// 地址通过后端获取
	        this.path = res.data.data
	        this.websock = new WebSocket('ws://' + this.path + ':8080/websocket/' + getUser())
	        this.websock.onopen = this.websocketonopen
	        this.websock.onerror = this.websocketonerror
	        this.websock.onmessage = this.websocketonmessage
	        // this.websock.onclose = this.websocketclose
	        // 路由跳转时结束websocket链接
	        /* this.$router.afterEach(function () {
	          this.websock.close()
	        }) */
	      })
	    },
	    // 打开连接
	    websocketonopen () {
	      this.websocketsend('hello')
	      console.log('WebSocket连接成功')
	    },
	     // 连接错误
	    websocketonerror (e) {
	      console.log('WebSocket连接发生错误')
	    },
	     // 数据接收
	    websocketonmessage (e) {
	      console.log(e)
	      console.log('数据已接收...')
	      // console.log(redata.value)
	    },
		 // 数据发送
	    websocketsend (agentData) {
	      this.websock.send(agentData)
	    },
		// 关闭连接
	    websocketclose () { 
	      console.log('connection closed')
	      this.websock.close()
	    },
	},
	data () {
	    return {
	      path: '',	// 保存ip地址
	      websock: '',	// 保存socket连接对象
		},
		created () {
			if (typeof (WebSocket) === 'undefined') {
			  alert('您的浏览器不支持socket')
			} else {
			  this.initWebsocket()	// 初始化websocket
			}
		}
	}
}
现象

在这里插入图片描述
注意:具体业务实现根据自己的应用场景通过后端进行数据推送

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值