微信小程序 implements WebSocket heartbeat reconnection
Recently, WebSocket was used in the development of 小程序. 小程序 provides the corresponding native API. There are some differences between the use of the H5 API. Therefore, some mature libraries of the popular H5 are somewhat difficult to use, and the native API has some defects. So I realized a set of heartbeat reconnection mechanism.
Conventionally, let's briefly introduce Websocket.
Websocket简介
Websocket是什么
WebSocket is a network communication protocol. RFC6455 defines its communication standard.
WebSocket is a protocol that HTML5 began to offer for full-duplex communication over a single TCP connection.
为什么需要Websocket
The HTTP protocol is a stateless, connectionless, one-way application layer protocol. It uses a request/response model. The communication request can only be initiated by the client, and the server responds to the request.
So when we want the server to send messages to the client, HTTP can't do it. We can only use polling or long polling to achieve similar functions. This way is inefficient and wastes resources. In order to solve such problems, WebSocket was born.
小程序中的WebSocket
小程序WebSocket的API
Leave you too lazy! Look at your official website!
为什么要做心跳重连
xx 使用本机WebSocket时,我们常常觉得它不稳定。客户端有时不会收到服务器发送的消息,或者客户端发送的消息服务器无法接收该消息。虽然WebSocket还提供了onError和onClose。方法,但通常会有各种未知因素导致断开而不会触发Error或Close事件。这导致实际连接断开,但客户端和服务器不知道,仍在等待消息。
所以我们必须解决的问题非常明确:
保证连接状态,连接断开时让客户端与服务端都能知道,进而重连。
上代码
页面载入后,我们连接socket先onLoad(){ this.linkSocket() }, linkSocket(){ let that = this wx.connectSocket({ url: app.globalData.wsUrl + 'websocket?' + this.data.taskId + '&' + this.data.userId, success() { console.log('连接成功') that.initEventHandle() } }) },复制代码
绑定事件
然后调用initEventHandle绑定各种事件
initEventHandle(){let that=this wx.onSocketMessage((res)=> {//接收消息})wx.onSocketOpen(()=> {console.log('WebSocket connection open')})wx。 onSocketError(function(res){console.log('WebSocket connection open failed')})wx.onSocketClose(function(res){console.log('WebSocket off!')})},复制代码我们把它放在这里,我们将在一段时间内填写
断线重连reconnect(){ if (this.lockReconnect) return; this.lockReconnect = true; clearTimeout(this.timer) if (this.data.limit<12){> { this.linkSocket(); this.lockReconnect = false; }, 5000); this.setData({ limit: this.data.limit+1 }) } },复制代码
我们设置锁定和最大重新连接数以避免无限重新连接。为了不对服务器施加太大压力,我每5秒设置一次重试,并请求最多12次。
修改initEventHandle,以便我们可以实现触发Error的断行的一般重新连接。
initEventHandle(){let that=this wx.onSocketMessage((res)=&gt; {//接收消息})wx.onSocketOpen(()=&gt; {console.log('WebSocket connection open')})wx。 onSocketError((res)=&gt; {console.log('WebSocket connection open failed')this.reconnect()})wx.onSocketClose((res)=&gt; {console.log('WebSocket is off!')this .reconnect()})},复制代码关键的来的---心跳对象
要尊重
设heartCheck={timeout: 10000,timeoutObj: null,serverTimeoutObj: null,reset: f沈阳软件customUnction(){clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj);归还这个; },start: function(){this.timeoutObj=setTimeout(()=&gt; {console.log('send ping')wx.sendSocketMessage({data:'ping',//success(){//console。 log('send ping success'); //}}); this.serverTimeoutObj=setTimeout(()=&gt; {wx .closeSocket();},this.timeout);},this.timeout);复制代码
心跳对象的心跳每10秒发送一次心跳。 timeoutObj和serverTimeoutObj是用于清除计时器的对象。 reset方法重置计时器并开始发送心跳。
继续转换我们的initEventHandle
initEventHandle(){ let that=this wx.onSocketMessage((res)=> { //received message if (res.data=='pong'){ heartCheck.reset().start() }else{ \\ Processing data } }) wx.onSocketOpen(()=>{ console.log('WebSocket connection open') heartCheck.reset().start() }) wx.onSocketError((res)=>{ console.log ('WebSocket connection failed to open') this.reconnect() }) wx.onSocketClose((res)=> { console.log('WebSocket is closed!') this.reconnect() }) }, copy codeWhen the connection is opened, call start to start the heartbeat, and send the message 'ping' to the server every 10 seconds. After receiving the message, the server will send us a message 'pong', just like 微信 chat.
Don't look at it, it's annoying. At least you can be sure that you are still friends, or if he pulls you black, you still don't know (a little off the mark)
If the server has not replied "pong" for more than 10 seconds, the connection is considered broken.
I rub, dare to delete my good friend, my Northeastern temper tantrum can this endure? I deleted you too. . Then quickly re-apply for a friend
xx 这是被调节的客户端直接关闭连接,调用closeSocket,但是一旦我们关闭了我们的onSocketClose事件并重新连接(slag man)
此时,心跳重新连接已完成
“沈阳软件公司”的新闻页面文章、图片、音频、视频等稿件均为自媒体人、第三方机构发布或转载。如稿件涉及版权等问题,请与
我们联系删除或处理,客服QQ:55506560,稿件内容仅为传递更多信息之目的,不代表本网观点,亦不代表本网站赞同
其观点或证实其内容的真实性。
热门文章
使用“扫一扫”即可将网页分享至朋友圈。