小程序怎么判断websocket断开

时间:2025-01-27 20:51:37 单机游戏

在微信小程序中,可以通过监听 `wx.onSocketClose` 事件来判断 WebSocket 是否断开。当 WebSocket 连接关闭时,会触发 `onSocketClosed` 回调函数,并携带错误信息。以下是一个示例代码,展示了如何在小程序中判断 WebSocket 断开并进行相应处理:

```javascript

// 在小程序的 Page 组件中定义变量和函数

Page({

data: {

isLogin: false,

heartCheck: true,

isClosed: false,

isReconnection: false,

_timeout: 30000 // 心跳检测超时时间,单位毫秒

},

onLoad: function () {

this.createWebSocket();

},

createWebSocket: function () {

const that = this;

const ws = new WebSocket('ws://your-websocket-url');

ws.onOpen = function () {

console.log('WebSocket 连接已打开');

that._isLogin = true;

that._startHeartCheck();

};

ws.onMessage = function (event) {

console.log('收到服务器消息:', event.data);

// 处理接收到的消息

};

ws.onClose = function (err) {

console.log('当前 WebSocket 连接已关闭,错误信息为:', JSON.stringify(err));

that._stopHeartCheck();

if (that._heartCheck) {

that._reset();

}

that._isLogin = false;

if (!that._isClosed) {

if (that._isReconnection) {

that._reConnect();

}

}

};

ws.onerror = function (error) {

console.error('WebSocket 发生错误:', error);

};

this.setData({

socket: ws

});

},

_startHeartCheck: function () {

const that = this;

const heartCheckInterval = setInterval(function () {

if (that._socket && that._socket.readyState === WebSocket.OPEN) {

that._socket.send('ping'); // 发送心跳消息

}

}, this._timeout);

this.setData({

heartCheckInterval: heartCheckInterval

});

},

_stopHeartCheck: function () {

clearInterval(this.data.heartCheckInterval);

},

_reset: function () {

// 重置连接相关变量

},

_reConnect: function (options) {

// 重新连接 WebSocket

},

_isClosed: function (socket) {

return socket && socket.readyState === WebSocket.CLOSED;

}

});

```

关键点解释:

监听 `onSocketClose` 事件:

当 WebSocket 连接关闭时,会触发 `onSocketClosed` 回调函数。

停止心跳检测:

在 `onSocketClosed` 回调函数中,如果心跳检测是启用的,则停止心跳检测。

关闭已登录开关:

将 `isLogin` 设置为 `false`,表示用户已退出小程序。

重连逻辑:

如果 `isReconnection` 为 `true`,则调用 `_reConnect` 方法进行重连。

心跳检测:

通过定时器每隔一段时间向服务器发送心跳消息,如果未收到服务器响应,则判定连接断开。

通过以上步骤,可以在小程序中有效地判断 WebSocket 是否断开,并进行相应的处理。