uniapp 长链接 socket 封装

App.vue

<script>
	import socket from '@/util/IM.js'
	export default {
		watch: {
			'$route': function() {
				var page = getCurrentPages();
				console.log('watch-监听路由', page);
			}
		},
		globalData: {
			ImAuth: socket.connect(),
		},
		onLaunch: function(e) {


		},
		onShow: function() {
			socket.ifReConnect = true
			socket.connect(false)
		},
		onHide: function() {
			socket.ifReConnect = false
			uni.closeSocket();
		}
	}
</script>

<style>
</style>

 

IM.js

// import JMessage from '@/static/jmessage-wxapplet-sdk-1.4.3.min.js';
import request from '@/util/request.js'
import api from "@/util/api.js";

// 长链接
var socket = {
		access_token: '',
		ifReConnect:true,//是否需要断线重连
		socketStatus: false, //连接状态
		socketTask: false, //当前长链接的对象
		connect: function(rePromise) {
			console.log('连接socket')
			socket.auth();
			let fc = (rePromise) => {
				request.request(api.IM.getImAccessToken).then(res => {
					socket.access_token = res.data.access_token;

					let url = `ws://xxx.cn/im/client/connect?access_token=${socket.access_token}`

					console.log('socket - url', url)
					socket.socketTask = uni.connectSocket({
						url: url,
						success: function(res) {
							socket.socketStatus = true;
							rePromise(socket.socketStatus)
						},
						fail: function(err) {
							socket.socketStatus = false;
							socket.connect(rePromise)
						},
					});
				});
			};
		return rePromise ? fc(rePromise) : new Promise(rePromise => fc(rePromise));
	},
	close:function(){
		socket.ifReConnect = false;
		console.log('WebSocket手动关闭!');
		uni.closeSocket();
	},
	auth: function(rePromise) {
		console.log('WebSocket初始化!');
		// 长链接监听
		uni.onSocketOpen((res) => {
			console.log('WebSocket连接已打开!', res);
		});
		
		uni.onSocketClose((res) => {
			console.log('WebSocket已关闭,是否允许重连', socket.ifReConnect);
			if(!socket.ifReConnect)return;
			// 如果是手动关闭或者其它不需要重连的状态就不重新链接 , 否则就断线重连
			setTimeout(()=>socket.connect(),1500)
		});
		
		uni.onSocketError((res) => {
			console.log('WebSocket出现错误,请检查!', res);
		});
	}
}

module.exports = socket;

 

相关推荐
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页
实付 49.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值