心跳websocket服务器时,返回多条相同的数(已解决)

wocall

问题描述

请教:
建立单列websocket,在不断开连接的情况下,使用leaveGroup和joinGroup来更换房间。
但是通过Gateway::sendToCurrentClient()「其它发送方法sendToUid、sendToClient也一样」发来的数据条数正好是更换房间的数量,而且每一条的内容完全一样。

这该如何解决。

客户端发送心跳,

sendPing() {
    if (this.socket) {
      this.socket.send({
        data: JSON.stringify({type: 'pong'};),
        success: (res) => {
          console.log('PingSr:', new Date());
        }
      });
    }
  }

服务器回复:

        case 'answer':    // 服务器回复pong 
            console.log('srPong!', data); 
            break;

客户端leave

socket.send({type: 'leave'});

服务端心跳回复:

            case 'pong':
                $new_message = array(
                    'type'=>'answer',
                    'time'=>date('Y-m-d H:i:s'),
                    'clients'=>Gateway::getAllClientSessions()
                );
                Gateway::sendToCurrentClient(json_encode($new_message));
                return;

服务端切换房间:

            //离开房间  
            case 'leave':
                $room_id = $_SESSION['room_id'];
                Gateway::leaveGroup($client_id, $room_id);
                return;

            //进入房间  
            case 'join':
                $uid = $message_data['uid'];
                $room_id = $message_data['room_id'];
                $_SESSION['room_id'] = $room_id;
                Gateway::joinGroup($client_id, $room_id);
                return;

切换多个房间后,微信开发者工具中竟是这样:

第一行为客户端心跳服务器
后面多行为服务端发来的数据:条数与房间数相同

不知为何,百思不得其姐!

550 3 0
3个回答

xiuwang

截图
这里看下是不是建立了多个连接。看下是不是js一次性发送了多个ping,看下服务端是否真的返回了多个pong。
这种问题基本上就是自己写的bug

  • wocall 2023-08-25

    感谢@ xiuwang

    无论显示回复有多少条相同的数据,发送和接收确实都是一条记录,这就奇了怪了:(

  • xiuwang 2023-08-25

    那应该是你前端代码有bug,在后端找问题方向就错了

  • wocall 2023-08-25

    您说的对,感谢感谢

wocall

感谢@ xiuwang

  • PHP甩JAVA一条街 2023-08-26

    你小程序切换, 后台, 销毁, 来电, 怎么重连监听wss?

  • wocall 2023-08-26

    我是做了个全局单列,进入小程序就让它一直连着。不管啥情况,只要发现断链就自动重新连接。打死也不让断的这种。。。。

  • PHP甩JAVA一条街 2023-08-27

    能学习下吗

PHP甩JAVA一条街
import websocket from './utils/wechat-websocket.js'

//app.js
App({
    onLaunch() {
        let _this = this;
        // 创建websocket对象
        this.websocket = new websocket({
            // true代表启用心跳检测和断线重连
            heartCheck: true,
            isReconnection: true
        });
        // 建立连接
        this.linkWebsocket();
        // 监听websocket状态
        this.websocket.onSocketClosed({
            url: this.globalData.websocketUrl,
            success(res) { console.log(res) },
            fail(err) { console.log(err) }
        })
        // 监听网络变化
        this.websocket.onNetworkChange({
            url: this.globalData.websocketUrl,
            success(res) { console.log(res) },
            fail(err) { console.log(err) }
        })
        // 监听服务器返回
        this.websocket.onReceivedMsg(onMessage => {
            console.log('app.js收到服务器内容:' + onMessage.data);
            // 要进行的操作
            var messageData = '';
            messageData = JSON.parse(onMessage.data);
            //缓存
            console.log(messageData);
            /*
            if (messageData.type == 'init' && messageData.client_id) {
                wx.setStorageSync('client_id', messageData.client_id);
            }
            */
            //反射函数
            if (this.onMessage) {
                this.onMessage(messageData);
            }
        })
    },
    onHide() {
        // 程序后台后的操作--关闭websocket连接
        this.websocket.closeWebSocket();
    },
    onShow() {
        // 程序从后台到前台的操作--建立连接
        this.linkWebsocket();
    },
    linkWebsocket() {
        // 建立连接
        this.websocket.initWebSocket({
            url: this.globalData.websocketUrl,
            success(res) { console.log(res) },
            fail(err) { console.log(err) }
        })
    },
    getWebSocket() {
        // 向其他页面暴露当前websocket连接
        return this.websocket;
    },
    globalData: {
        websocketUrl: 'wss://xzb..vip:443/wss',
        //websocketUrl: 'ws://127.0.0.1:7272',
        baseUrl: 'https://xzb..vip',
        //baseUrl: 'http://127.0.0.1:96',
    }
})
export default class websocket {
  constructor({ heartCheck, isReconnection }) {
    // 是否连接
    this._isLogin = false;
    // 当前网络状态
    this._netWork = true;
    // 是否人为退出
    this._isClosed = false;
    // 心跳检测频率
    this._timeout = 3000;
    this._timeoutObj = null;
    // 当前重连次数
    this._connectNum = 0;
    // 心跳检测和断线重连开关,true为启用,false为关闭
    this._heartCheck = heartCheck;
    this._isReconnection = isReconnection;
    this._onSocketOpened();
  }
  // 心跳重置
  _reset() {
    clearTimeout(this._timeoutObj);
    return this;
  }
  // 心跳开始
  _start() {
    let _this = this;
    this._timeoutObj = setInterval(() => {
      wx.sendSocketMessage({
        // 心跳发送的信息应由前后端商量后决定
        data: JSON.stringify({
          uid: wx.getStorageSync('uid')
        }),
        success(res) {
          console.log(res)
          console.log("发送心跳成功");
        },
        fail(err) {
          console.log(err)
          _this._reset()
        }
      });
    }, this._timeout);
  }
  // 监听websocket连接关闭
  onSocketClosed(options) {
    wx.onSocketClose(err => {
      console.log('当前websocket连接已关闭,错误信息为:' + JSON.stringify(err));
      // 停止心跳连接
      if (this._heartCheck) {
        this._reset();
      }
      // 关闭已登录开关
      this._isLogin = false;
      // 检测是否是用户自己退出小程序
      if (!this._isClosed) {
        // 进行重连
        if (this._isReconnection) {
          this._reConnect(options)
        }
      }

    })
  }
  // 检测网络变化
  onNetworkChange(options) {
    wx.onNetworkStatusChange(res => {
      console.log('当前网络状态:' + res.isConnected);
      if (!this._netWork) {
        this._isLogin = false;
        // 进行重连
        if (this._isReconnection) {
          this._reConnect(options)
        }
      }
    })
  }
  _onSocketOpened() {
    wx.onSocketOpen(res => {
      console.log('websocket已打开');
      // 打开已登录开关
      this._isLogin = true;
      // 发送心跳
      if (this._heartCheck) {
        this._reset()._start();
      }
      // 发送登录信息
      wx.sendSocketMessage({
        // 这里是第一次建立连接所发送的信息,应由前后端商量后决定
        data: JSON.stringify({
          uid: wx.getStorageSync('uid')
        })
      })
      // 打开网络开关
      this._netWork = true;
    })
  }
  // 接收服务器返回的消息
  onReceivedMsg(callBack) {
    wx.onSocketMessage(msg => {
      if (typeof callBack == "function") {
        callBack(msg)
      } else {
        console.log('参数的类型必须为函数')
      }
    })
  }

  // 建立websocket连接
  initWebSocket(options) {
    let _this = this;
    if (this._isLogin) {
      console.log("您已经登录了");
    } else {
      // 检查网络
      wx.getNetworkType({
        success(result) {
          if (result.networkType != 'none') {
            // 开始建立连接
            wx.connectSocket({
              url: options.url,
              success(res) {
                if (typeof options.success == "function") {
                  options.success(res)
                } else {
                  console.log('参数的类型必须为函数')
                }
              },
              fail(err) {
                if (typeof options.fail == "function") {
                  options.fail(err)
                } else {
                  console.log('参数的类型必须为函数')
                }
              }
            })
          } else {
            console.log('网络已断开');
            _this._netWork = false;
            // 网络断开后显示model
            wx.showModal({
              title: '网络错误',
              content: '请重新打开网络',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
          }
        }
      })
    }
  }
  // 发送websocket消息
  sendWebSocketMsg(options) {
    wx.sendSocketMessage({
      data: options.data,
      success(res) {
        if (typeof options.success == "function") {
          options.success(res)
        } else {
          console.log('参数的类型必须为函数')
        }
      },
      fail(err) {
        if (typeof options.fail == "function") {
          options.fail(err)
        } else {
          console.log('参数的类型必须为函数')
        }
      }
    })
  }
  // 重连方法,会根据时间频率越来越慢
  _reConnect(options) {
    let timer, _this = this;
    if (this._connectNum < 20) {
      timer = setTimeout(() => {
        this.initWebSocket(options)
      }, 3000)
      this._connectNum += 1;
    } else if (this._connectNum < 50) {
      timer = setTimeout(() => {
        this.initWebSocket(options)
      }, 10000)
      this._connectNum += 1;
    } else {
      timer = setTimeout(() => {
        this.initWebSocket(options)
      }, 450000)
      this._connectNum += 1;
    }
  }
  // 关闭websocket连接
  closeWebSocket() {
    wx.closeSocket();
    this._isClosed = true;
  }
}
  • PHP甩JAVA一条街 2023-08-27

    后台用老大写的GatewayWorker, 做的打牌记账小程序, 一年没重启了, 比JAVA还稳

🔝