pladaria / reconnecting-websocket

Reconnecting WebSocket. For Web, React Native, cli (Node.js)
MIT License
1.22k stars 197 forks source link

How to use "reconnecting-websocket" in Browsers & Node.js? #18

Closed bennycode closed 7 years ago

bennycode commented 7 years ago

Hello, I want to write an TypeScript application which connects to a WebSocket and can be used in Browsers & Node.js environments. Here is my code:

import * as NodeWebSocket from 'ws';
const ReconnectingWebsocket = require('reconnecting-websocket');

export default class WebSocketClient {
  private socket: WebSocket;

  constructor(public baseURL: string) {}

  public connect(): Promise<WebSocket> {
    const reconnectingOptions = {
      connectionTimeout: 4000,
      constructor: (typeof window !== 'undefined') ? WebSocket : NodeWebSocket,
      debug: true,
      maxReconnectionDelay: 2000,
      maxRetries: Infinity,
      minReconnectionDelay: 1000,
      reconnectionDelayGrowFactor: 1.0,
    };

    this.socket = new ReconnectingWebsocket(baseURL, undefined, reconnectingOptions);
    this.socket.binaryType = 'arraybuffer';

    return new Promise((resolve) => {
      this.socket.onopen = () => {
        resolve(this.socket);
      };
    });
  }
}

When I run my code it looks like I am getting a WebSocket connection:

RWS: init
RWS: connect
RWS: bypass properties
RWS: open
RWS: reconnectDelay: 1791.0727462657023

Unfortunately, there is nothing coming through socket.onmessage, so I don't receive any message events.

When working with the Node.js "ws" module it works:

import * as WebSocket from 'ws';

export default class WebSocketClient {
  private socket: WebSocket;

  constructor(public baseURL: string) {}

  public connect(): Promise<WebSocket> {
    this.socket = new WebSocketClient(baseURL);
    this.socket.binaryType = 'arraybuffer';

    return new Promise((resolve) => {
      this.socket.onopen = () => {
        resolve(this.socket);
      };
    });
  }
}

But then I don't have a reconnecting WebSocket (which I really would like to have!). 😢

bennycode commented 7 years ago

Ok, I found out how to make it work for Browsers (using Webpack) and on Node.js (https://github.com/wireapp/wire-web-api-client/pull/69). Thanks for providing this beautiful library! 🍻