deor

uWebSockets.js Pong Behavior for maintaining connection status

You can use the pong websocket behavior to maintain a connection status when using uWebSockets.js, instead of just assuming a user is still connected between open & close. uWebSockets.js pings the client every 90 seconds by default, and by listening to the pong event, you can hook into the pong response from the client to keep track of the connection status.

public socketServer: uWebSockets.TemplatedApp = uWebSockets.App();

.
.
.

const behavior: WebSocketBehavior<UserData> = {
  upgrade: async (res, req, context) => {
    try {
      let aborted = false;
      res.onAborted(() => {
        aborted = true;
      });

      if (aborted) {
        return;
      }

      res.upgrade(
        // Any user data here you want to assign to the websocket, like api key, id, etc
        { id: Math.random().toString(36).substring(2) },
        req.getHeader('sec-websocket-key'),
        req.getHeader('sec-websocket-protocol'),
        req.getHeader('sec-websocket-extensions'),
        context
      );
    } catch (err) {
      // This only happens if the user disconnects DURING the upgrade operation
    }
  },
  open: (ws) => this.newConnection(ws),
  message: (ws, message) => this.messageEvent(ws, message),
  close: (ws) => this.closeEvent(ws),
  pong: (ws) => {
    // Do any logic here you want to let your stack know a user is stil connected
    this.updateConnection(ws.id);
  },
};
this.socketServer.ws<UserData>('/*', behavior);
this.socketServer.listen('0.0.0.0', 3000);