UNI-APP_WebSocket长连接封装

socket.js

import {
	VUE_APP_WS_URL
} from "@/utils/index.js";
const Socket = function() {

	// this.ws.close(this.close.bind(this));
};


// #ifdef H5
function wss(wsSocketUrl) {
	let ishttps = document.location.protocol == 'https:';
	if (ishttps) {
		return wsSocketUrl.replace('ws:', 'wss:');
	} else {
		return wsSocketUrl.replace('wss:', 'ws:');
	}
}
// #endif



Socket.prototype = {
	// close() {
	//   clearInterval(this.timer);
	//   this.ws.close();
	// },
	onSocketOpen: function(my) {
		uni.$emit('socketOpen', my)
	},
	init: function() {
		var that = this;
		this.timer = setInterval(function() {
			that.send({
				type: "ping"
			});
		}, 10000);
	},
	send: function(data) {
		let datas = JSON.stringify(data)
		return uni.sendSocketMessage({
			data: datas
		});
	},
	onMessage: function(res) {
		const {
			type,
			data = {}
		} = JSON.parse(res.data);
		uni.$emit(type, data)
	},

	onClose: function() {
		uni.closeSocket()
		clearInterval(this.timer);
		uni.$emit("socket_close");
	},
	onError: function(e) {
		uni.$emit("socket_error", e);
	},
	close: function() {
		uni.closeSocket();
	},
	onStart: function(token, form_type) {
		let wssUrl = `${VUE_APP_WS_URL}`
		this.ws = uni.connectSocket({
			url: wssUrl + '?type=user&token=' + token + '&form_type=' + form_type,
			header: {
				'content-type': 'application/json'
			},
			method: 'GET',
			success: (res) => {}
		});
		this.ws.onOpen(this.onSocketOpen.bind(this))
		this.ws.onError(this.onError.bind(this));
		this.ws.onMessage(this.onMessage.bind(this))
		this.ws.onClose(this.onClose.bind(this));
	}
};

Socket.prototype.constructor = Socket;
export default Socket;

兼容支付宝小程序版

import {
	VUE_APP_WS_URL
} from '@/config/app.js'
const Socket = function() {

	// this.ws.close(this.close.bind(this));
};


// #ifdef H5
function wss(wsSocketUrl) {
	let ishttps = document.location.protocol == 'https:';
	if (ishttps) {
		return wsSocketUrl.replace('ws:', 'wss:');
	} else {
		return wsSocketUrl.replace('wss:', 'ws:');
	}
}
// #endif



Socket.prototype = {
	// close() {
	//   clearInterval(this.timer);
	//   this.ws.close();
	// },
	onSocketOpen: function(my) {
		uni.$emit('socketOpen', my)
	},
	init: function() {
		var that = this;
		this.timer = setInterval(function() {
			that.send({
				type: "ping"
			});
		}, 10000);
	},
	send: function(data) {
		let datas = JSON.stringify(data)
		// #ifdef MP-ALIPAY
		return this.ws.send({
			data: datas
		})
		// #endif
		// #ifndef MP-ALIPAY
		return uni.sendSocketMessage({
			data: datas
		});
		// #endif
	},
	onMessage: function(res) {
		const {
			type,
			data = {}
		} =
		// #ifdef MP-ALIPAY
		JSON.parse(res.data.data);
		// #endif
		// #ifndef MP-ALIPAY
		JSON.parse(res.data);
		// #endif
		uni.$emit(type, data)
	},

	onClose: function() {
		uni.closeSocket()
		clearInterval(this.timer);
		uni.$emit("socket_close");
	},
	onError: function(e) {
		uni.$emit("socket_error", e);
	},
	close: function() {
		uni.closeSocket();
	},
	onStart: function(token, form_type) {
		let wssUrl = `${VUE_APP_WS_URL}`
		this.ws = uni.connectSocket({
			url: wssUrl + '?type=login&token=' + token,
			header: {
				'content-type': 'application/json'
			},
			method: 'GET',
			// #ifdef MP-ALIPAY
			multiple: true,
			// #endif
			success: (res) => {}
		});
		this.ws.onOpen(this.onSocketOpen.bind(this))
		this.ws.onError(this.onError.bind(this));
		this.ws.onMessage(this.onMessage.bind(this))
		this.ws.onClose(this.onClose.bind(this));
	}
};

Socket.prototype.constructor = Socket;
export default Socket;

main.js

import socket from './libs/socket.js'
Vue.prototype.$socket = new socket();

使用

onLoad(options) {
	uni.showLoading({
		title: '客服连接中...'
	});
},
onUnload() {
	this.$socket.onClose();
	uni.$off()
},
onReady() {
	//链接长连接
	this.$socket.onStart(this.$store.state.app.token, form_type);
	// 链接成功
	uni.$once('success', () => {
		console.log('连接成功')
		this.$socket.init();
	});
	uni.$once('socketOpen', () => {
		// 	登录
		this.$socket.send({
			data: this.$store.state.token,
			type: 'login'
		});
		this.$nextTick(e => {
			this.getChatList();
		})
	});


	// 发送消息
	this.$socket.send({
		data: {
			token: this.$store.state.token,
		},
		type: 'login'
	});
	uni.$on('socket_error', () => {
		this.$util.Tips({
			title: '连接失败'
		});
	});
	// 消息接收
	uni.$on('login', data => {
		console.log('res::', data);
	});
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值