uniapp+websocket实现在线聊天

首先在进入程序的时候对后台进行链接,注意这里的链接地址必须是wss开头

        chatConnect({
            commit,
            state
        }) {
            let token = uni.getStorageSync('token');
            let userID = uni.getStorageSync('userID');
            console.log('------------------vuex里面的------------', uni.getStorageSync('token'), uni.getStorageSync('userID'))
            let url = `wss://www.xxx.com?userID=${userID}&token=${token}`; //服务器地址
            return websocket.connect(
                url,
                res => {
                    if (JSON.parse(res.data).key === 'pang') {
                        // console.log('心跳连接没问题')
                        app.globalData.heartCheck.reset().start(); //心跳     
                    } else {
                        console.log('返回的聊天数据', JSON.parse(res.data));
                        commit('saveChatOneMsg', JSON.parse(res.data));
                        commit('saveUnreadMsgArr', JSON.parse(res.data));
                        if (state.unreadMsgArr.length > 0) {
                            let num = state.unreadMsgArr.length;
                            console.log('app.vue中的未读消息', state.unreadMsgCount, store.state.unreadMsgArr.length);
                            uni.setTabBarBadge({
                                index: 1,
                                text: num.toString()
                            });
                        }
                        console.log('------------------------------分隔符-----------------------');
                    }
                });
        }

websock的链接方法
用到的api:
uni.connectSocket
uni.onSocketOpen
uni.onSocketMessage
uni.onSocketError
uni.onSocketClose

async function connect(url, func) {
    let msglist=[]
    if(uni.getStorageSync('userID')){
        msglist = await getMessageGroup()
    }
    uni.connectSocket({
        url: url,
        header: {
            'content-type': 'application/json'
        },
        success: function() {
             console.log('websocket连接成功~')
        },

        fail: function(res) {
            // console.log('websocket连接失败~', res)
            if (msglist && msglist.length > 1) {
                reconnect()
            }

        }
    })

    uni.onSocketOpen((res) => {
        //接受服务器消息
        uni.onSocketMessage(func); //func回调可以拿到服务器返回的数据
        uni.sendSocketMessage({
            data: JSON.stringify({
                content: '',
                key: 'ping',
                userID: uni.getStorageSync('userID'),
                messageType: 0,
                weight: 0,
                height: 0,
                groupID: 0,
                seq: 0
            }),
        });

    });
    uni.onSocketError(function(res) {
        // uni.showToast({
        //  title: 'websocket连接失败,请检查!',
        //  icon: "none",
        //  duration: 2000
        if (msglist && msglist.length > 1) {
            reconnect()
        }
        // })
    })

    uni.onSocketClose((res) => {
        console.log('方法里面的WebSocket 已关闭!',res); 
        reconnect()
    });

}

由于websocket在与服务器进行链接的时候有可能会断开,所以在最开始就加上了心跳,在断开的时候进行重链接。这个方法定义在App.vue上,直接在原型链上定义该方法,通过调用api uni.sendSocketMessage一直向服务器发送消息来判断是否断开。

  globalData: {
    unReadMsg: [],
    unReadMsgCount: 2,
    heartCheck: {
      timeout: 10000,
      timeoutObj: null,
      serverTimeoutObj: null,
      reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
      },
      start: function () {
        this.timeoutObj = setTimeout(() => {
          // console.log('发送ping',);
          uni.sendSocketMessage({
            data: JSON.stringify({
              content: '',
              key: 'ping',
              userID: uni.getStorageSync('userID'),
              messageType: 0,
              weight: 0,
              height: 0,
              groupID: 0,
              seq: 0
            })
          });
          this.serverTimeoutObj = setTimeout(() => {
            uni.closeSocket();
          }, this.timeout);
        }, this.timeout);
      }
    }
  }

websocket重链接方法

let limit = 0
let timer = null
let lockReconnect = false

function reconnect() {
    let token = uni.getStorageSync('token');
    let userID = uni.getStorageSync('userID');
    let url = `wss://www.xxx.com?userID=${userID}&token=${token}`; //服务器地址
    console.log('--------------重连了没------------重连的url', url)
    if (lockReconnect) return;
    lockReconnect = true;
    clearTimeout(timer)
    if (limit < 12) {
        timer = setTimeout(() => {
            connect(url);
            lockReconnect = false;
        }, 5000);
        limit += 1
    }
}

最后就是每次发送消息的时候调用api uni.sendSocketMessage就可以发送信息,进行愉快的聊天了

function send(msg) {
    uni.sendSocketMessage({
        data: msg
    });
}

微信图片_20210205175141.jpg
微信图片_20210205175145.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。