微信小程序如何连接websocket

在需要启用的地方调用app.js中的openScoket()函数;停用的地方调用closeSocket()函数

// app.js
App({
    onLaunch() {
        // 如果存在相关信息,连接websocket
        if ( this.globalData.socketStatus === 'closed') {
            this.openScoket();
        }
    },
    // 打开websocket连接
    openScoket() {
        const token = wx.getStorageSync('yun_token').token || "";
        const uuid = wx.getStorageSync('schoolMsg').uuid || "";
        // 打开信道(通过 WebSocket 连接发送数据。需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。)
        wx.connectSocket({
            url: "",
            header: { //请求头
                'content-type': 'application/json',
            },
            timeout: 7000,
            success: () => {
                console.log("websocke连接成功");
            },
            fail: (err) => {
                if (err) {
                    console.log("wx.connectSocket连接失败", err)
                }
            },
            complete: () => {
                // console.log("websocke连接完成")
            }
        });
        //监听 WebSocket 连接打开
        wx.onSocketOpen(() => {
            console.log('WebSocket 已打开连接,并且连接成功');
            this.globalData.socketStatus = 'connected';
        })
        //断开时的动作
        wx.onSocketClose(() => {
            console.log('WebSocket 已断开');
            this.globalData.socketStatus = 'closed';
            //断线重连
            this.reconnect();
        })
        //报错时的动作
        wx.onSocketError(error => {
            console.error('socket error出错了:', error);
            this.reconnect();
        })
        // 监听服务器推送的消息
        wx.onSocketMessage(message => {
            //把JSONStr转为JSON
            message = message.data.replace(" ", "");
            if (typeof message != 'object') {
                message = message.replace(/\ufeff/g, ""); //重点
                const msg = JSON.parse(message);
                message = msg;
            }
            //callback函数对服务端发送的消息进行处理
            this.globalData.callback(message);
            // console.log("监听到如下数据发送变化:", message);
        })
    },
    //关闭websocket连接
    closeSocket() {
        if (this.globalData.socketStatus === 'connected') {
            wx.closeSocket({
                success: () => {
                    this.globalData.socketStatus = 'closed';
                    console.log("websocket连接已关闭")
                }
            })
        }
    },
    //发送消息函数
    sendMessage(data) {
        if (this.globalData.socketStatus === 'connected') {
            const msg = JSON.stringify({
                
            })
            wx.sendSocketMessage({
                data: msg
            })
        }
    },
    // 断线重连
    reconnect() {

        let timer = null;
        if (this.globalData.socketStatus === 'closed') {
            console.log("断线重连中......");
            timer && clearTimeout(timer);
            timer = setTimeout(() => {
                this.openScoket();
            }, 500)
        } else {
            this.closeSocket();
        }
    },
    onHide() {
        // 断开websocket连接
        this.closeSocket();
    },
    //app 全局属性监听
    globalData: {
        socketStatus: 'closed',
        callback: function () {}
    }
})

callback函数在各页面中的应用方法

const app = getApp();

Page({
  wacthWebsocket() {
      const that = this;//这里需要注意this指向问题
      app.globalData.callback = function (msg) {
         //这里写对msg进行处理的业务逻辑
      }
   },
})

你可能感兴趣的:(微信小程序,微信小程序,websocket,javascript)