针对微信小程序中Tcp的连接,断开,重连以及心跳机制,以下代码做了简单的实现,有需求的可参考。
接收消息时候我做了事件处理,以便每个页面可正常处理消息。
App({
globalData: {
isConnected: false,
socketTask: null,
serverHostname: 'example.com',
serverPort: 80,
heartbeatInterval: 5000, // 心跳包间隔时间,单位为毫秒
heartbeatTimer: null
},
onShow: function () {
if (!this.globalData.isConnected) {
this.connectToServer();
}
},
connectToServer: function () {
let that = this;
this.globalData.socketTask = wx.createTCPSocket();
this.globalData.socketTask.onConnect(() => {
console.log('连接成功');
that.globalData.isConnected = true;
// 开始心跳包定时发送
that.startHeartbeat();
});
this.globalData.socketTask.onError((res) => {
console.log('连接出错', res);
that.globalData.isConnected = false;
that.stopHeartbeat(); // 停止发送心跳包
});
this.globalData.socketTask.onClose(() => {
console.log('连接关闭');
that.globalData.isConnected = false;
that.stopHeartbeat(); // 停止发送心跳包
});
// 连接服务器
this.globalData.socketTask.connect({
hostname: this.globalData.serverHostname,
port: this.globalData.serverPort,
success: function () {
console.log('连接成功');
},
fail: function (res) {
console.log('连接失败', res);
that.globalData.isConnected = false;
that.stopHeartbeat(); // 停止发送心跳包
}
});
},
startHeartbeat: function () {
let that = this;
this.globalData.heartbeatTimer = setInterval(() => {
if (that.globalData.isConnected) {
// 发送心跳包数据
that.sendHeartbeatData();
}
}, this.globalData.heartbeatInterval);
},
sendHeartbeatData: function () {
// 向服务器发送心跳包数据的逻辑
// 可以是一个简单的数据包,用于告知服务器连接仍然有效
// 如果长时间没有收到服务器的响应,可以在这里处理重新连接的逻辑
},
stopHeartbeat: function () {
clearInterval(this.globalData.heartbeatTimer);
}
});