websocket使用

考虑到登录之后要始终连接服务器接收消息,所以把websocket实例对象作为模块抛出,在main.js中引入,使全局都可以获得ws并且使用相关方法。
由于刷新页面时,ws会自动断开连接,所以在App.vue组件挂载时再次连接服务器。
utils/websocket.js
该文件位置任意,引入的时候注意路径即可

export default {
    ws: {},
    setWs: function(newWs) {
        this.ws = newWs
    },
    start(){// 发送心跳
        clearInterval(this.timeoutObj)
        this.timeoutObj = setInterval(() => {
            if (this.ws && this.ws.readyState === 1) {
                console.log('发送心跳')
                this.ws.send(JSON.stringify({
                    //后端需要接收的数据
                }));
            }
        }, 10 *1000)//十秒发一次
    },
    localSocket(userId) {//连接ws,根据连接服务器是否需要参数设置该方法是否需要接收参数
        if ("WebSocket" in window) {
            // console.log("您的浏览器支持 WebSocket!");
            // location.host
            this.ws = new WebSocket('这里要填连接服务器的地址');
            this.setWs(this.ws);
            this.ws.onopen = ()=>{
                console.log('websocket连接成功');
                //连接上之后要发心跳包
                this.start()
            };

            this.ws.onclose =  ()=> {
                // 关闭 websocket
                console.log("连接已关闭...");
                //断线重新连接
                setTimeout(() => {
                    this.localSocket(userId);
                }, 2000);
            };
        } else {
            // 浏览器不支持 WebSocket
            console.log("您的浏览器不支持 WebSocket!");
            this.openNotificationWithIcon('error', '浏览器', '您的浏览器不支持显示消息请更换', 1,1)
        }
    },
} 

import global from '@/utils/websocket'
Vue.prototype.global = global

mounted(){
      this.global.localSocket(userId)
      //连上之后要接收服务器发来的消息
      this.global.ws.onmessage = (msg)=>{
          console.log(JSON.parse(msg.data))
       }
}

第二种方法,直接写在.vue文件中

//////websocket
		contactSocket() {
			let webSocket = null;
			let socketOpen = false;
			let that = this
			if ("WebSocket" in window) {
				webSocket = new WebSocket("wss://10.44.166.5:81/websocket/biological/websocket");
				webSocket.onopen = function () {
					console.log("连接成功!");
					webSocket.send({
						"command": "device_status",
						"time": "16655155",
						"command_id": "eef10d68-86f1-4251-bdc0-76bafbf5962e",
						"device_type": "fingerprint",
						"data": { "figer_type": "left_hand" }
					})
					socketOpen = true

				};
				webSocket.onmessage = function (evt) {
					let received_msg = evt.data;
					console.log("接受消息:" + received_msg);
				};
				webSocket.onclose = function () {
					console.log("连接关闭!");
					setTimeout(() => {
						that.reconnect()
					}, 3000);

				};
				webSocket.onerror = function () {
					console.log("连接异常!");
				};
			}
		},
		// 重连
		reconnect() {
			console.log('重新连接')
			this.contactSocket()
		},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端段

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值