Giter VIP home page Giter VIP logo

reconnecting-websocket's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reconnecting-websocket's Issues

Webpack?

How can I use this library with webpack? Using this doens't work...

import ReconnectingWebsocket from 'reconnecting-websocket'

Support for Cookie header in React Native

I'm reopening this since this library wants to support React Native. And in websockets that depend on cookies (such as Spring), you need to be able to pass a cookie header.

I found that in current versions of React Native, you have to pass this header as an option like so

new WebSocket(url, protocols, {
    headers: {
         Cookie: [actual cookie data]
    }
});

This option is undocumented but apparent in the source code.
I would hope that this real life RN scenario can be supported. #35

Cannot send "code" and "reason" to server in close command

I need to send a code (other that the default 1000) to my server. I cannot get it to work.

Here is what I'm using:

  • Client: React Native 0.45 with reconnecting-websocket
  • Server: Node.js with ws

I can verify the following:

  1. Server gets code=1000, reason=""
  2. In ReconnectingWebsocket.close() I have verified (console.log) that code=1003 right before ws.close(code, reason) is called

I cant understand what's wrong. The only logical explanation I can come up with is that React Native's implementation of WebSocket sends code=1000 and reason="" as hard coded values.

I have probably missed something though. Anyone else having trouble with this?

Support immediate reconnect

I have some code which periodically monitors the connection by sending an application-specific ping message and waiting for a response. If no response is received, I would like to disconnect and immediately attempt to reconnect (with no delay, since I've already delayed a long time waiting for the ping response). However, if the first reconnection attempt fails, I would like to delay additional reconnect attempts using the current reconnectDelay logic.

ReconnectingWebsocket.close() accepts a delay parameter that can be used to override reconnectDelay. However, if I set this to a low value (like 1) and the first reconnection attempt fails, then subsequent reconnect attempts will happen too rapidly.

Any suggestions for how to deal with this situation? Could another flag be added to close() to trigger an immediate reconnect without interfering with the existing reconnectDelay logic on subsequent reconnects if the immediate reconnect fails?

Add bower support

I'd love to include this into some projects on the browser, but we normally use bower to install our components. Could you please add support for bower?
Thank you!

"beforeReconnect" & "afterReconnect" callbacks

We have a use case where we need to execute a function before every WebSocket reconnect. It would be great if the ReconnectingWebsocket instance could execute a function (like beforeReconnect) on every reconnect.

Another option, to fulfill our needs, would be making use of Promises for getUrl. But this requires the ReconnectingWebsocket to wait for a Promise to resolve.

Idea:

const getUrl = () => Promise.resolve('ws://echo.websocket.org/?id=something_special');
const rws = new ReconnectingWebSocket(getUrl);

TypeError in Safari 9.1.2

I get a TypeError: WebSocket constructor not set. Set "options.constructor" error message in Safari 9.1.2 (11601.7.7) when using browserify 13.1.0 and reconnecting-websocket.

Test to reproduce:

browserify -r reconnecting-websocket:websocket > websocket.js

<!DOCTYPE HTML>
<html>
<head>
<script src="websocket.js" type="text/javascript"></script>
</head>
<body>
<script>
    var websocket = require('websocket');

    var ws = new websocket('ws://localhost:1337');
</script>
</body>
</html>

OS I'm using is Mac OS X 10.11.6 (15G31) El Capitan.

Cannot access underlying WebSocket

I am using the npm ws Websocket in a node.js app and I would like to use the Websocket.ping() method to keep my connection alive. However, the ping() method is not implemented in ReconnectingWebsocket and I don't see a way to access the Websocket instance that was created within ReconnectingWebsocket.

Would you be open to adding a method or property that provides access to the underlying Websocket? That would make any current or future methods and/or properties in a Websocket implementation available while still using ReconnectingWebsocket.

The other option would be to implement the ping method, but it may not be supported in all Websocket implementations just yet.

Force closing

If you call .close() when there's no network, the native (browser) websocket waits until timeout and then closes.

Add an option to close() so that it can force close without waiting and try to open a new one.

How to set protocol

I set up the new object as follows,

var options = {connectionTimeout: 1000};
var reconnectingWebSocket = new ReconnectingWebsocket('wss://localhost:9090', null, options);

but in the Chrome console, it showed:

Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

I don't have any idea to fix it. Can someone help me? Thanks.

error in use

i use 'reconnecting-websocket' in my project.but there is a error that i can't fix it. the error occured on using module 'reconnecting-websocket',but it dismissed while use 'ws'. sorry for poor English,i'm chinese.

var ReconnectingWebSocket = require('reconnecting-websocket');
var options = {constructor:WebSocket,debug: true, reconnectInterval: 3000};
var regWs = new ReconnectingWebSocket(config.server,[], options);
// var regWs = new WebSocket("ws://127.0.0.1:60001");
regWs.on('open', function() {
regNode(regWs);
});
regWs.on('error', function(e) {
console.log('error occured:'+e);
});
regWs.on('close', function() {
console.log('closed');
});
regWs.on('message', function(message) {
var msg = {};
try{
msg = JSON.parse(message);
}catch(e){
console.log('unresolved msg:'+message);
}
processMessage(msg,regWs);
});

RWS: init
RWS: connect
RWS: bypass properties
error occured:Error: connect ECONNREFUSED 127.0.0.1:60001
RWS: handleClose { shouldRetry: true }
RWS: retries count: 1
RWS: handleClose - reconnectDelay: 1620.2790890714393
closed
events.js:163
throw er; // Unhandled 'error' event
^

Error: connect ECONNREFUSED 127.0.0.1:60001
at Object.exports._errnoException (util.js:1050:11)
at exports._exceptionWithHostPort (util.js:1073:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
RWS: connect
RWS: bypass properties

Typescript defs for close are missing third argument

ReconnectingWebsocket extends WebSocket but doesn't redefine the close method to take the third "options" parameter.

Closing a reconnecting websocket like this:

rws.close(1000, '', opts);

Results in a typescript error; Expected 0-2 arguments, but got 3.

Change WebSocket connection URL during runtime

Our backend at Wire requires an access token as part of the WebSocket connection URL.

The schema looks like this:

wss://prod-nginz-ssl.wire.com/await?access_token=Dp42wWHPiGukagf86Djx7JvVKed

The access token must be renewed at a certain interval which leads to problems when using ReconnectingWebsocket because it will still try to reconnect to the URL it has been initialized with (which could have an outdated access_token).

Is there a chance to change the connection URL at runtime? Telling from the type definitions it doesn't look like it's accessible. ๐Ÿ˜ข

Does not start retrying when connection drops

If there is no connection available when trying to connect this plugin works great, it does exactly as expected and tries to reconnect untill the connection can be established.

But in my case it can happen that the connection can drop after a stable connection has already been made and then the plugin does not try to reconnect... Is this possible with the current plugin or should we discuss a way how to implement this, because I think it's a must have feature ;)

Using:

"reconnecting-websocket": "4.0.0-rc5",
"ws": "5.2.0"`

Edit:
Closed because duplicate #60

Failing test: level0 event listeners are reassigned after reconnect

I forked "reconnecting-websocket", did npm install and ran npm test. Unfortunately, the tests are failing on my machine (Windows 10, Node.js v8.4.0):

Failing test: level0 event listeners are reassigned after reconnect
Reason: Planned for 26 assertions, but got 27.

Screenshot:

Screenshot

SyntaxError if used with Webpack and UglifyJs

Version 4.0.0-rc3 throws an SyntaxError if used with Webpack and UglifyJs:

SyntaxError: Unexpected token: name (Event) [../~/reconnecting-websocket/dist/reconnecting-websocket-cjs.js:3,0]

Version 3.2.2 can be used without any errors

use of cookie header

I use Spring Websocket on the server side and the version I work with, basically uses a sessionid to get into the authenticated areas. Is there a way to add a header that gets sent with the connection attempt?

No messages received after reconnect.

It is very odd. The reconnecting-websocket works very well showing a reconnect after a server is restarted. I also see data being sent thought this websocket, but for some odd reason, after a reconnect, my on message function is no longer called. It is very simple code. Any ideas what I'm doing wrong?
I get messages the first time the code is run, but after a reconnect, the "On Message" is never executed.

const WebSocket = require('ws');
const ReconnectingWebSocket = require('reconnecting-websocket');
var socketUrl = instance.options.url;
instance.debug("WebSocket: Connect to: "+socketUrl);
instance.websocket = new ReconnectingWebSocket(socketUrl,[],{ constructor: WebSocket, debug: true });
instance.websocket.on('message', function(data) {
  console.log("On Message");
});
instance.websocket.on('close', function close() {
  console.log('disconnected');
});

Cannot send messages using `reconnecting-websocket` (works with vanilla `WebSocket`)

I am so lost. I cannot send messages using this library. Using the browser's WebSocket (as can be seen in the minimal example below), works fine. I am using a simple server configuration to echo all messages received using https://www.npmjs.com/package/ws.

const ws = new ReconnectingWebSocket(`ws://${location.hostname}:5000`)

ws.onopen = () => {
  ws.send('test')
}
// Gives 'test' in node.js console
const ws = new WebSocket(`ws://${location.hostname}:5000`)

ws.onopen = () => {
  ws.send('test')
}
// Nothing in node.js console

I have read through the code and I have no clue why this would be happening. You don't appear to be doing anything fancy with ws.send. Any suggestions?

onclose behaviour has changed -- was it intentional?

I noticed my application was failing to reconnect after the reconnecting-websocket rewrite. Upon investigation, I realised this seems to be because this library no longer reconnects when a websocket is intentionally closed by the server -- a close event is triggered but nothing else happens.

Previously, a graceful server-side close event would trigger a reconnect:

setTimeout(connect, reconnectDelay);

...but now the reconnect is not triggered:

The reconnect mechanism is triggered on error so I suspect this is an intentional change.

What do you think about adding a reconnectOnClose option, on by default?

Alternatively the docs could be updated to clarify this behaviour, and perhaps suggest manually binding a reconnect such as:

rws.addEventListener('close', () => rws.reconnect());

Although that seems to cause thrashing if the connection cannot be established, as reconnect calls _disconnect which calls the handlers again.

Thanks for the well written library.

receive a imcomplete message

I use golang implement the websocke server and reconnecting-websocket in browser;the server log print the server send the complete message to the browser, but the browser only recevie imcomplete message.

const ws = new ReconnectingWebSocket("ws://" + url, undefined, {debug: true});

    ws.onmessage = e => {
        if (typeof e.data === "string") {
            emitter(JSON.parse(e.data));
        } else {
            console.debug("[WebSocket] get data is not string, but", typeof e.data, "e:", e)
        }
    };

browser throw error of JSON.parse(), and the receive data is below:

{"type":"FETCH_ASSESSMENTS_SUCCESSED","payload":{"n

Better instructions for using reconnecting-websocket in browser client

Using this package in a browser client application (instead of from a Node.js application) does not seem to be sufficiently covered in the documentation.

That is, the simple case

const ReconnectingWebSocket = require('reconnecting-websocket');
const rws = new ReconnectingWebSocket('ws://my.site.com');

rws.addEventListener('open', () => {
    rws.send('hello!');
});

does not work out-of-the-box because it requires RequireJS client-side. And getting reconnecting-websocket to work in combination with RequireJS isn't trivial, as even the troubleshooting section at http://requirejs.org/docs/errors.html#notloaded does not clearly provide solutions for getting it working.

I guess that a basic instruction "How/where to install reconnecting-websocket in your client-side web application directory structure" would help out greatly.

Release 3.2.2 on npm differs from GitHub Release 3.2.2.

Hi,

PR #32 was merged (yay!) and 3.2.2 was published but I noticed that the index.d.ts (from commit d4c121e) differs from the one published on npm (to be found in reconnecting-websocket-3.2.2.tgz).

diff --git a/npm/dist/index.d.ts b/d4c121ec2a/dist/index.d.ts
index 11799e8..d4c3b0e 100644
--- a/npm/dist/index.d.ts
+++ b/d4c121ec2a/dist/index.d.ts
@@ -1,6 +1,5 @@
 interface ReconnectingWebsocket extends WebSocket {
     [key: string]: any;
-    close(code?: number, reason?: string, config?: {keepClosed: boolean, fastClose: boolean, delay: number}): void;
 }
 declare const ReconnectingWebsocket: (url: string | (() => string), protocols?: string | string[], options?: {
     [key: string]: any;

Is it possible that you re-published after removing the changes from #32?

Provide timestamp of next connection attempt

I'd like to inform the user that there's a connectivity problem, and when the next attempt will be to restore the connection. To do that, I'd have to know when the websocket will attempt to reconnect (e.g. through a timestamp property on the ReconnectingWebSocket object that tells when the next connection attempt will be).

npm ERR! missing script: start

I've been trying to run this project but at the end of the npm install process as well as when trying to execute npm start i get this following message. I know there is a bunch of tracks on the web about this issue, but i yet haven't figure it out a way to get it sorted. Any help woud be appreciated.

$ npm start
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start"
npm ERR! node v6.10.3
npm ERR! npm v3.10.10

npm ERR! missing script: start
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
npm ERR! C:\workspace\repositorios_projetos-piloto-testes\reconnecting-websocket\npm-debug.log

Doesn't work for GDAX (node)

The module doesn't manage to stay connected to the [GDAX] crypto data feed:

const WebSocket = require('ws');
const ReconnectingWebSocket = require('reconnecting-websocket');
const rws = new ReconnectingWebSocket('wss://ws-feed.gdax.com', [], {
  constructor: WebSocket,
  debug: true,
});

let lastPointTimestamp = new Date();
setInterval(() => {
  if (Date.now() - lastPointTimestamp > 60 * 1000)
    // No data in the past minute since we got called
    console.warn('Got disconnected and did not reconnect');
}, 60 * 1000);

function handleData(data) {
  lastPointTimestamp = Date.now();
  console.log(data.price);
}

rws.on('open', () => {
  rws.send(JSON.stringify({
    type: 'subscribe',
    product_ids: ['BTC-USD'],
    channels: ['matches'],
  }));
});
rws.on('message', data => handleData(JSON.parse(data)));
rws.on('error', err => {
  console.error('ON ERROR -', err);
});

The log shows this:

ON ERROR - { Error: read ECONNRESET
    at _errnoException (util.js:1003:13)
    at TLSWrap.onread (net.js:620:25) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' }
RWS: handleClose { shouldRetry: true }
RWS: retries count: 1
RWS: handleClose - reconnectDelay: 2043.1049894719274
RWS: connect
RWS: bypass properties
RWS: timeout

abount error keyword "ETIMEDOUT"

From the source code found retriesCount > config.maxRetries error, return the keyword "ETIMEDOUT", and timeout connection is the same, is it right? Can you consider the two keywords to distinguish between what? If not? Can you tell me why?

thanks

npm ERR! missing script: start

I've been trying to run this project but at the end of the npm install process as well as when trying to execute npm start i get this following message. I know there is a bunch of tracks on the web about this issue, but i yet haven't figure it out a way to get it sorted. Any help woud be appreciated.

$ npm start
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start"
npm ERR! node v6.10.3
npm ERR! npm v3.10.10

npm ERR! missing script: start
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
npm ERR! C:\workspace\repositorios_projetos-piloto-testes\reconnecting-websocket\npm-debug.log

Opens too many WebSockets

I am having hard time reproducing this issue consistently, however every once in a while a single instance of ReconnectingWebSocket seems to create two WebSocket connections at the same time. It even reconnects both of these two instances automatically.

My code boils down to this:

const webSocket = new ReconnectingWebSocket('ws://localhost:1234/' + uniqueToken(), [], {
    maxReconnectionDelay: 10000,
    minReconnectionDelay: 100,
    reconnectionDelayGrowFactor: 1.5,
    connectionTimeout: 2000,
    maxRetries: Infinity,
});
webSocket.addEventListener('open', event => {
    webSocket.binaryType = 'arraybuffer';
    // start sending stuff
});
webSocket.addEventListener('message', event => {
    // do something with event.data
});
webSocket.addEventListener('close', event => {
    // logging
});
webSocket.addEventListener('error', event => {
    // logging
});

(In the logs of the server I find that both of the connections are using the same unique id in the URL)

React Native cookie

I am recieveing the response of an api call from the cookie. I tried many ways but i failed to fetch the details.How can i do .I tried react native fetch call and also library react-native-cookies.

idex.d.ts

i saw ReconnectingWebsocket have close method with params blew:
close(code?: number, reason?: string, params?: any): void;
can this added to idex.d.ts , i want to use this method with params

this._listeners.error is undefined

I'm running into the following scenario, I'm providing incorrect URL on perpouse with 0 retry option.
const options = {
connectionTimeout: 500,
maxRetries: 0,
debug: true
};
const rws = new ReconnectingWebSocket('ws://**lokalhost**:8080', [], options);

Registering on error event listener:

rws.addEventListener('error' , (evt: any): any => {
                        if (evt.message === 'TIMEOUT') {
                            // do something here
                        }
                    };

Looks like any registered listener is removed on connection error and never get called from the internal _handleError

 _handleError(event) {
            this._debug('error event', event.message);
            this._disconnect(undefined, event.message === 'TIMEOUT' ? 'timeout' : undefined);
            if (this.onerror) {
                this.onerror(event);
            }
            this._debug('exec error listeners');
            **this._listeners.error.forEach(listener => listener(event));**
            this._connect();
        }

getting this error TypeError: this._listeners.error is undefined

Any recommendations how to handle initial connection errors ?

send() succeeds silently when underlying websocket is not initialized yet

    /**
     * Enqueues the specified data to be transmitted to the server over the WebSocket connection
     */
    public send(data: string | ArrayBuffer | Blob | ArrayBufferView) {
        if (this._ws) {
            this._ws.send(data);
        }
    }

Result: message is lost, but application code thinks everything is OK.

Real-life example of such occurrence:

const socket = new ReconnectingWebSocket(url);
// The main thread continues execution before ReconnectingWebSocket._ws is initialized.
// Maybe because of setTimeout() and Promises in ReconnectingWebSocket._connect logic?
socket.send("MSG");
// No exceptions, all send() calls are lost before _ws is initialized

Handling of ECONNREFUSED

Hi,

I'd like to start a connection before the server is up and keep retrying until the connection is finally accepted. I'm using 'ws' in node.js as the underlying ws implementation.
The problem with this is the 'close' event comes before 'open' (actually no 'open' comes, only a 'close' and an 'error'), so the timeout handler is not removed and I get the following error during the second try:

RWS: init
RWS: connect
RWS: bypass properties
error:  { Error: connect ECONNREFUSED 127.0.0.1:8167
    at Object.exports._errnoException (util.js:1024:11)
    at exports._exceptionWithHostPort (util.js:1047:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1150:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8167 }
RWS: handleClose { shouldRetry: true }
RWS: retries count: 1
RWS: handleClose - reconnectDelay: 2940.596362061423
Connection closed:  1006
RWS: connect
RWS: bypass properties
RWS: timeout
events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: closed before the connection is established
    at WebSocket.close (<project>\node_modules\ws\lib\WebSocket.js:270:28)
    at Timeout._onTimeout (<project>\node_modules\reconnecting-websocket\dist\index.js:126:16)
    at ontimeout (timers.js:469:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:264:5)

Extract from my code:

const ReconnectingWebSocket = require('reconnecting-websocket');
const WebSocket = require('ws');
this.ws = new ReconnectingWebSocket(url, [], {constructor: WebSocket, debug: true});

this.ws.on('error', (data) => {
   console.log('error: ', data);
});

this.ws.on('close', (code, reason) => {
   console.log('Connection closed: ', code, reason);
   this.connectionStatus = 'disconnected';
});

Is there any workaround for this? Is this an issue with reconnecting-websocket or ws?

open/close events are firing only once

const WebSocket = require('ws');
const ReconnectingWebSocket = require('reconnecting-websocket');

const wss = new WebSocket.Server({ port: 8084 });

wss.on('connection', (client, req) => {
  client.send('msg');
  setTimeout(() => {
    client.close()
  }, 1000);
});

let rws = new ReconnectingWebSocket('ws://127.0.0.1:8084', [], { 'constructor': WebSocket });
rws.addEventListener('open', e => {
  console.log('open');
});
rws.addEventListener('message', e => {
  console.log('msg');
});
rws.addEventListener('close', e => {
  console.log('close');
});

output:

open
msg
close
msg
msg
msg
...

npm install failed

npm install
npm WARN prepublish-on-install As of npm@5, prepublish scripts will run only for npm publish.
npm WARN prepublish-on-install (In npm@4 and previous versions, it also runs for npm install.)
npm WARN prepublish-on-install See the deprecation note in npm help scripts for more information.

[email protected] prepublish C:\projects\reconnecting-websocket\reconnecting-websocket
npm run clean && npm run build && npm run build-amd && npm test

[email protected] clean C:\projects\reconnecting-websocket\reconnecting-websocket
rimraf dist

[email protected] build C:\projects\reconnecting-websocket\reconnecting-websocket
tsc

[email protected] build-amd C:\projects\reconnecting-websocket\reconnecting-websocket
tsc -m AMD --outFile ./dist/reconnecting-websocket.amd.js

[email protected] test C:\projects\reconnecting-websocket\reconnecting-websocket
nyc --reporter=text-summary --reporter=lcov ava --verbose --serial test/test.js

โˆš throws with invalid constructor
โˆš throws if not created with new
โˆš global WebSocket is used if available (1s)
โˆš url provider
โˆš connection status constants
โˆš max retries (3s)
ร— level0 event listeners are reassigned after reconnect Planned for 26 assertions, but got 27.
โˆš level0 event listeners are reassigned after closing with fastClose (166ms)
โˆš level2 event listeners (addEventListener, removeEventListener) (4s)

  • connection timeout
    โˆš connect, send, receive, close {fastClose: false}
    โˆš connect, send, receive, close {fastClose: true}
    โˆš close and keepClosed (107ms)
    โˆš debug mode logs stuff (1s)
    โˆš #14 fix - closing with keepClose before open (1s)

1 test failed [10:10:03]
1 test skipped

level0 event listeners are reassigned after reconnect

C:\projects\reconnecting-websocket\reconnecting-websocket\test\test.js:90

89:
90: t.plan(26); // 5 ECONNREFUSED + 1 EHOSTDOWN + 5 * 4 t.is()
91: const handleOpen = () => {};

Planned for 26 assertions, but got 27.

=============================== Coverage summary ===============================

Statements : 100% ( 145/145 )
Branches : 100% ( 64/64 )
Functions : 100% ( 31/31 )
Lines : 100% ( 132/132 )

npm ERR! Test failed. See above for more details.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] prepublish: npm run clean && npm run build && npm run build-amd && npm test
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prepublish script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\jiajun.xiong\AppData\Roaming\npm-cache_logs\2018-05-08T02_10_03_996Z-debug.log

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

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!). ๐Ÿ˜ข

Expose retriesCount ?

Will you consider to expose retriesCount to user ? So that users can show this count somewhere.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.