Uniapp断网重连

oop86868j8j

问题描述

大佬们能分享个稳定的Uniapp断网重连的代码吗?

1521 2 1
2个回答

augushong

这是我之前写的聊天写过的。
其实很简单,监听一下事件就行。
其实麻烦的还是onMessage的业务监听

import tools from "@/assets/js/tools.js";
import store from '@/util/store';
let socketResource = null;
let socketTimer = null;
let sound = null;
const socket = {
    currentChat: null,

    init(options) {

        if (socketResource != null) {
            return true;
        }

        console.log(options)
        if (typeof options == 'undefined') {
            options = {};
        }

        if (options.onSuccess == undefined) {
            options.onSuccess = function() {}
        }

        console.log(options)

        console.log('长链接初始化')

        socketResource = uni.connectSocket({
            url: tools.wssHost, //仅为示例,并非真实接口地址。
            success: (res) => {
                socketTimer = setInterval(() => {
                    this.send({
                        type: "ping",
                    });
                }, 10000);
                console.log('调用onSuccess回调')

                setTimeout(() => {
                    options.onSuccess()
                }, 300)
            },
            fail(e) {
                console.log('建立连接失败', e);
                setTimeout(() => {
                    socket.restartInit()
                }, 1200)
            }
        });

        socketResource.onMessage((revice) => {

        })

        socketResource.onError((e) => {
            console.log('长链接错误:', e)

            socketResource.close()
            socket.restartInit()

        })

        socketResource.onClose(() => {
            socket.restartInit()
        })
    },

    restartInit() {

        socketResource = null;
        clearInterval(socketTimer)
        socketTimer = null;
        setTimeout(() => {
            console.log('关闭长链接并重新初始化')
            socket.init({
                onSuccess: () => {
                    console.log('执行重启回调')
                    socket.login()
                }
            });
        }, 300)
    },

    login() {
        this.send({
            type: "login",
        });
    },

    send(item) {

    },

}

export default socket;
chaz6chez

webman/push
workbunny/webman-push-server
这两个插件中都有uniapp的样例

  • 暂无评论
年代过于久远,无法发表回答
×
🔝