针对微信小程序中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