CxSocket a smart wechat websocket plug-in

Background: Recently small program mall is doing websocket optimization request performance. Compared with wechat’s stream listening function call, it is easy to corrupt with the complexity and iteration of business code. Hence the encapsulation.

What do we need to think about when we do this? The author makes the following single point of consideration

  1. Mini event management system, compared to the native events all in onClose chain events, here supports chain calls, and can repeatedly subscribe to events
  2. Caching policy mechanism, yes, even websocket, we still add caching. The reason is that Websocket has the possibility and risk of disconnection, so we can make up for the communication gap during disconnection through cache, which is a degradation strategy
  3. Reconnection strategy: When the loss is detected, we need to reconnection, but it is likely that there is a reconnection failure of the payment request, at this time, the reconnection times and interval strategy need to be weighed and balanced in the limited resources.

The event type

export enum CxSocketEvents {
    open = 'open',
    close = 'close',
    error = 'error',
    message = 'message',
    retry = 'retry'
}
Copy the code

use

Create a Websocket instance by using the CxSocketCreator constructor. The parameters are as follows. For details, refer to the wechat API

type IAnyObject = Record<string, any> export interface ConnectParam { url: string, header? : IAnyObject, protocols? : string[], tcpNoDelay? : boolean, perMessageDeflate? : boolean, timeout? : number, success? : () => {}, fail? : () => {}, complete? : () => {}}Copy the code
 const ws = new CxSocketCreator({
  url: 'ws://test123.hello.com:8000/zj/ws'
})
.onOpen((i, ev) => { console.log("opened") })
.onClose((i, ev) => { console.log("closed") })
.onError((i, ev) => { console.log("error") })
.onMessage((i, ev) => { console.log("message") })
.onRetry((i, ev) => { console.log("retry") })
.build()
Copy the code

Multiple calls

const ws = new CxSocketCreator({ url: 'ws://test123.hello.com: 8000 / what zj had/ws'}) onMessage ((I, e) = > {the console. The log (" send ")}). The onMessage ((I, (e) = > {i. end e.d ata)}) onMessage ((I, e) = > {the console. The log (" received information ")}). The build ();Copy the code

Event to remove

ws.removeEventListener(CxSocketEvents.open, targetListener);
Copy the code

reconnection

When WS is disconnected, we need to consider the reconnection strategy. Here we consider two retraining strategies

ConstantGapEmit

ConstantBackoff will always request a connection at a fixed time until the connection is ready. Use ConstantBackoff to send requests 1s apart:

const ws  = new CxSocketCreator('ws://test123.hello.com:8000/zj/ws'). WithBackoff (new ConstantBackoff(1000)) // 1000ms = 1s
    .build();
Copy the code
LinearGapEmit

This policy sets the start time, interval time, and end time relative to the previous one. As shown in the following example, the face flushing attempt starts at 0s every 1s and automatically gives up at 8s

const ws  = new CxSocketCreator('ws://test123.hello.com:8000/zj/ws'). WithBackoff (new LinearBackoff(0.1000.8000))
    .build();
Copy the code

Disconnect the data cache

When we disconnect, we cache requests from the client to the server, and when we reconnect, we throw back the cached data. The cache market and data volume are formally mentioned below

LRUBuffer

As the name suggests, we cache the latest n entries and flush out any additional entries

Const ws = new CxSocketCreator (' ws://test123.hello.com: 8000 / what zj had/ws). WithBuffer (new LRUBuffer (1000)). The build ();Copy the code

TimeBuffer

The timeBuffer policy will cache the latest n seconds of data, data exceeding n seconds will be discarded

Const ws = new CxSocketCreator (' ws://test123.hello.com: 8000 / what zj had/ws). WithBuffer (new TimeBuffer (5 * 60 * 1000)). The build ();Copy the code