便利贴--37{uni + websocket 使用}

27 篇文章 0 订阅
10 篇文章 0 订阅

便利贴--37{uni + websocket 使用}

基本

带自动重连,自动心跳发送

使用情况

// import $store from '../index.js'
// import vueconfig from '../../vue.config.js'
import Wst from './lid/websocketL.js'
import WxStorage from "../static/lib/wxStorage.js" //微信Storage

// var url = 'ws://' + vueconfig.devServer.proxy["/cloud"].target.substring(5) + '/websocket';
import $store from './index.js'
import apis from "./apiConfig.js"
// let url = 'ws://192.168.0.108:9034/websocket';
// let url = 'ws://223.82.109.183:2082/websocket';
let url = apis.wsapi;

const webSockets = new Wst(url);

let websocket = {
	state: {
		webSockets: webSockets, //websocket实例
		socket: '', //websoclet主体
		socketValue: '', //接收的数据
		socketState: false, // 当前连接websocket状态
		socketInterval: false, //心跳
		socketTimeout: false, //检测服务器是否连接成功timeout
		socketInterTime: 5000, //心跳时间 秒*1000
		socketStateMY: true, //总控  在退出登入时,强行关闭心跳
	},
	actions: {
		connectws({
			state,
			commit
		}) {
			console.log("开启websocket")
			var getValue = function(res) { // 消息回调
				commit("setSocketValue", res);
			}
			var getState = function(res) { // 状态回调
				commit("setState", res);
			}
			var getws = function(res) { // 主体回调
				commit("setSocket", res);
			}
			// console.log(webSockets.$callBack)
			// let equipmentInformation = navigator.userAgent;
			// var Data = {
			// 	router: "share",
			// 	res: {
			// 		...$store.state.logs.user,
			// 		equipmentInformation: equipmentInformation
			// 	},
			// }
			var ws = webSockets.$callBack(getValue, getState, getws, state.puserID || WxStorage.get("ids"))
				.$connect();

		},
	},
	mutations: {
		wsOut(state, value) {
			webSockets.$outws();
		},
		setSocket(state, value) { //websocket主体
			state.socket = value;
		},
		setSocketValue(state, value) {
			console.log(value, 222222222222)
			// if (value.router) { //正常数据返回
			// 	//去除心跳数据
			// 	if (value.router == 'share/heartbeat') {
			// 		return;
			// 	}
			console.log(value)
			state.socketValue = value;
			// 	console.log(value, 'websocket信息')
			// } else { //异常数据返回
			// 	console.log(value, '异常')
			// }
		
		},
		//本地建造数据传递
		setMyvalue(state, value) {
			state.socketValue = value;
		},
		setsocketStateMY(state, value) {
			state.socketStateMY = value;
		},
		setState(state, value) {
			state.socketState = value;
		},
	}
}

export default websocket


源码

// uniapp版本websocket总控制

function Wst(url) {
	this.url = url || "";
	this.ws = "";
	this.ourControl = true; //总控
	this.state = false;
	this.timeIntval = false;
	this.timeIntvalTime = 5000;
	this.WebSocketValue = "";
	this.backValue = function(res) {
		console.log(res, "未设置msg返回函数");
	};
	this.getws = "";
	this.Data = "";
	this.heartBeat = "";
	this.loginData = "";

	this.ids = '';
	return this;
}

Wst.prototype.$callBack = function(getValue, getState, getws, ids) {
	// console.log("设置回调函数")
	this.backValue = function(res) {
		if (!getValue && !getState) {
			console.log(res, "未设置msg返回函数");
		} else {
			if (getValue) {
				getValue(res);
			}
			if (getState) {
				getState(this.state);
			}
		}
	};
	this.getws = getws;
	this.ids = ids;
	return this;
};

Wst.prototype.$connect = function(Data) {
	// console.log("开启")
	this.ourControl = true;
	let that = this;
	this.Data = Data;
	this.loginData = {
		id: this.ids,
		type: 'login'
	};
	this.heartBeat = 'ping';
	this.ws = uni.connectSocket({
		url: that.url,
		success(data) {
			console.log(data, "websocket连接成功");
		},
	});
	// console.log(that.url)
	this.ws.onOpen((res) => {
		// 注:只有连接正常打开中 ,才能正常成功发送消息
		// console.log("发送登入消息 websocket")
		// console.log(that.loginData)
		that.ws.send({
			data: JSON.stringify(that.loginData),
			async success(res) {
				// console.log(res, "登入成功"); //设置登入成功状态 并开启心跳
				that.state = true;
				that.$heartbeat();
			},
		});
		// 注:只有连接正常打开中 ,才能正常收到消息
		that.ws.onMessage((res) => {
			// console.log("收到服务器内容:", JSON.parse(res.data));
			let d = res.data;
			try {
				d = JSON.parse(res.data);
			} catch (e) {}
			that.WebSocketValue = d;
			// that.state = true;
			// this.$heartbeat();
			that.backValue(d);
		});
	});
	// this.ws.onClose((e) => {
	// 	console.log(11111111111111111)
	// 	that.state = false;
	// 	that.backValue(e);
	// });
	// this.$heartbeat();
	this.getws(this.ws);
	return this;
};

Wst.prototype.$heartbeat = function() {
	let that = this;
	let open = function() {
		// console.log('开启心跳');

		that.ws.send({
			data: that.heartBeat,
		});
	};
	let rel = function() {
		console.log('重新连接');
		that.$connect(that.Data);
	};
	if (that.timeIntval) {
		clearInterval(that.timeIntval);
	}
	that.timeIntval = setInterval(() => {
		if (!this.ourControl) {
			return;
		}
		// console.log(that.state)
		if (that.state) {
			open();
		} else {
			rel();
		}
	}, that.timeIntvalTime);
};

Wst.prototype.$outws = function() {
	this.ourControl = false;
	clearInterval(this.timeIntval);
	this.timeIntval = false;
	this.WebSocketValue = {};
	this.state = false;
	// this.backValue({});
};

export default Wst;


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

轻动琴弦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值