Giter Site home page Giter Site logo

reconnecting-websocket's Introduction

ReconnectingWebSocket

A small JavaScript library that decorates the WebSocket API to provide a WebSocket connection that will automatically reconnect if the connection is dropped.

It is API compatible, so when you have:

var ws = new WebSocket('ws://....');

you can replace with:

var ws = new ReconnectingWebSocket('ws://....');

Minified library with gzip compression is less than 600 bytes.

How reconnections occur

With the standard WebSocket API, the events you receive from the WebSocket instance are typically:

onopen
onmessage
onmessage
onmessage
onclose // At this point the WebSocket instance is dead.

With a ReconnectingWebSocket, after an onclose event is called it will automatically attempt to reconnect. In addition, a connection is attempted repeatedly (with a small pause) until it succeeds. So the events you receive may look something more like:

onopen
onmessage
onmessage
onmessage
onclose
// ReconnectingWebSocket attempts to reconnect
onopen
onmessage
onmessage
onmessage
onclose
// ReconnectingWebSocket attempts to reconnect
onopen
onmessage
onmessage
onmessage
onclose

This is all handled automatically for you by the library.

Parameters

var socket = new ReconnectingWebSocket(url, protocols, options);

url

protocols

options

  • Options (see below)

Options

Options can either be passed as the 3rd parameter upon instantiation or set directly on the object after instantiation:

var socket = new ReconnectingWebSocket(url, null, {debug: true, reconnectInterval: 3000});

or

var socket = new ReconnectingWebSocket(url);
socket.debug = true;
socket.timeoutInterval = 5400;

debug

  • Whether this instance should log debug messages or not. Debug messages are printed to console.debug().
  • Accepts true or false
  • Default value: false

automaticOpen

  • Whether or not the websocket should attempt to connect immediately upon instantiation. The socket can be manually opened or closed at any time using ws.open() and ws.close().
  • Accepts true or false
  • Default value: true

reconnectInterval

  • The number of milliseconds to delay before attempting to reconnect.
  • Accepts integer
  • Default: 1000

maxReconnectInterval

  • The maximum number of milliseconds to delay a reconnection attempt.
  • Accepts integer
  • Default: 30000

####reconnectDecay

  • The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist.
  • Accepts integer or float
  • Default: 1.5

timeoutInterval

  • The maximum time in milliseconds to wait for a connection to succeed before closing and retrying.
  • Accepts integer
  • Default: 2000

maxReconnectAttempts

  • The maximum number of reconnection attempts that will be made before giving up. If null, reconnection attempts will be continue to be made forever.
  • Accepts integer or null.
  • Default: null

binaryType

  • The binary type is required by some applications.
  • Accepts strings 'blob' or 'arraybuffer'.
  • Default: 'blob'

Methods

ws.open()

  • Open the Reconnecting Websocket

ws.close(code, reason)

ws.refresh()

  • Refresh the connection if still open (close and then re-open it).

ws.send(data)

  • Transmits data to the server over the WebSocket connection.
  • Accepts @param data a text string, ArrayBuffer or Blob

Like this? Check out websocketd for the simplest way to create WebSocket backends from any programming language.

Follow @joewalnes

Bitdeli Badge

reconnecting-websocket's People

Contributors

andrewconner avatar artfulhacker avatar bitdeli-chef avatar border-radius avatar dcolens avatar drewnoakes avatar dsri avatar jakobud avatar jamesthorpe avatar joewalnes avatar josh avatar koto avatar ondrejsika avatar relekang avatar uecasm avatar wjt avatar yutopp avatar

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  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

reconnecting-websocket's Issues

"onreconnect" event?

Would it be a good idea to add the onreconnect event?

I am controlling the "reconnect" event at "onopen", which is helping me to force resend the last message on a queue, but not on the first connection open event.

It's a very simple example, but could help to realise that it should be a good idea.

Thanks.

Bower-Version

It would be nice to introduce versions of "reconnecting-websocket" to bower. That would help to reduce the risk of having problems with a new version (see Issue #44).

Prevent reconnect when connection was closed by server

I would like to use this library to automatically reconnect in case of network failure.
When the server closes the connection, the client should not reconnect.
Currently this is not possible, after a close + time-out we always reconnect.
There should be a way for the user of the library to decide, based on the close event to whether a reconnect should happen.

How do I run this inside a webworker?

it's looking for the document inside the webworker code, presumably to check if it's supported.

Uncaught ReferenceError: document is not defined

Is there a way of avoiding this, I would like to run the reconnectingwebsocket inside a webworker

Thanks!

JS error on page reload in Chrome

Hi. Any ideas on annoying JS error (Chrome 47.0.2526.106 m):
"WebSocket connection to 'ws://ws.url.tld' failed: A server must not mask any frames that it sends to the client."
Showing up exactly on page reload right before unloading, fired from line 209 of your script, which is exactly
ws = new WebSocket(self.url, protocols || []);

Error does not affect functionality - but this looks unclear)

Thannks

Suggestion to Improvement for support method ws.binaryType = "arraybuffer"

Hi,
I'm using ReconnectionWebSocket (very good function!)

But I encourage in provide support to: "ws.binaryType = "arraybuffer" ;
It will be used when receive Blog images;

For example bellow way works very well ๐Ÿ‘

var ws=new WebSocket("ws://......")
ws.binaryType = "arraybuffer";

It not works ๐Ÿ‘Ž

 var ws=new ReconnectingWebSocket("ws://......",null,  {binaryType:"arraybuffer",debug: false,reconnectInterval: 4000});
 ws.binaryType = "arraybuffer";

Pausing to reconnect websocket

As I leave my system idle/hibernate. Following error comes in the console.
core.es5.js:1020 ERROR INVALID_STATE_ERR : Pausing to reconnect websocket.

After the error, I never get any update from the socket until I refresh the tab.

Updating URL in between onClose reconnects

So I have a case where my URL contains an OAuth token (for authentication), kind of like this:

ws://localhost:8080/myapp/webapi/subscriptions?bearer_token=aba58cfd6ecbb9532e6308683d2accbd

It is possible that the session gets closed because the token is invalid (due to a timed out access token). In this case I would want to refresh my access token, update the URL and then try again to reconnect. I think, if we add an optional callback that this framework allowed to update the URL in between reconnects that would solve the problem. Something like this:

"function setUrlBetweenReconnects() {
... callback code here
}"

Or alternatively, if we specify an optional parameter string, that can be updated between reconnects, so initially I would set parameters to be "bearer_token=aba58cfd6ecbb9532e6308683d2accbd" and then in between reconnects you call "updateParameters()" which calls a method I set/override.

Any of this seem reasonable or can you think of a better way to solve this problem?

Nodejs

Is this a nodejs library? How to use it in nodejs?
npm install ?

Reconnection is not always triggered

Sometimes, when the connection is lost and back up again (for example laptop goes in standby, and then i re-open it and reconnect to the wifi) the websocket re-connection is not triggered. But it can take about 5 or 10 minutes, and sometimes it doesn't reconnect at all. I believe this also depends on the browser (in Safari this happens all the time for me).
Is there a way to trigger or check the connection periodically, without having to implement something like a custom ping/pong that involves server coding?
Thank you.

reconnect attempts only when ...

In a mobile scenario, often the internet connection is not available. In that case it doesn't seem to make sense, and I wouldn't be surprised if it was detrimental to battery life, to keep trying to reconnect.

It might be interesting to add a function reference that returns a boolean on whether to attempt a reconnect at all. This function could in a mobile scenario return true if connected and false if offline.

Reconnecting event

Hi,

Thanks! This is very useful add-on.

I have a question: is there any event provided on reconnecting-websocket?
Better if we have ones similar like: onReconnectStart and onReconnectSuccess, so we can display status like "Reconnecting..." and "Connection re-established" or something like that :-)

Thanks,
Arief D

onclose() event object is missing code, reason, & wasClean

The onclose() event object is missing keys like code, reason, and wasClean. After some investigation I realized that the event returned to the user is a CustomEvent instead of the CloseEvent returned by native sockets. It looks like in line 266 you are creating a custom event:

if (!reconnectAttempt && !timedOut) {
        if (self.debug || ReconnectingWebSocket.debugAll) {
                   console.debug('ReconnectingWebSocket', 'onclose', self.url);
        }
        eventTarget.dispatchEvent(generateEvent('close')); //<== creating custom event
}

In doing this, the keys, event.code, event.reason, and event.wasClean are stripped and essentially lost in translation, giving the user no useful information to the reason the connection was closed.

For some background, I'm hoping to use these keys to determine if the connection was closed on purpose or due to some connection issue, and to re-send the last message if there was an issue with the connection.

Is this project abandoned?

I'm looking for a websocket library just like this and at first glance it looked popular, issues are being ignored and there haven't been and pushes in almost a year.

Should I look elsewhere if I have no interest in "fixing it myself" if something goes wrong under the hood?

Thanks!

Onconnecting can't be overridden quick enough

I have this:

socket = new ReconnectingWebSocket("wss://push.planetside2.com/streaming?service-id=s:ps2maps");
socket.debug = true;
socket.onconnecting = function(e) {
  console.log("Websocket connecting........", e);
  return true;
};

I never see my message even though I get a successful connection. The problem is that the websocket tries to make a connection before the event handler can be overridden, so it never registers. Later, after a connection is made, I can manually (in dev tools) run:

socket.onconnecting() and now I see my message.

How would you solve this problem? One of the problems I've always seen about websockets is that they attempt to make a connection upon creation, which I think is a terrible idea. Its impossible to create a websocket without connecting immediately.

I think that is where your library could be improved. This is what I think needs to happen:

  1. Provide an option to create the reconnecting websocket object without actually making a connection. (ie, without creating a Websocket object). This would be something in the constructor, like:
var socket = new ReconnectingWebSocket("http://whatever.com", null, false);

The 3rd optional parameter would be a boolean (open when creating or not) that would default to true. That way backwards compatibility is maintained.

  1. Next, provide a manual .open() method that is used to manually make the connection. I made a pull request for this feature recently but it looks like the project code base has significantly changed since then. No big deal, its an easy one for me to rewrite. I know there is a refresh() method already, but if you manually close(1000), the socket connection for whatever reason, then refresh won't do anything. If there is a close() there needs to be an open().

These two options would allow you to create a reconnecting websocket without creating a websocket. Then you can define all your event handlers. Then you can manually connect. Then everything works great.

The HTML5 WebSocket API is not perfect, and this is a great opportunity for this library to fix some of the downfalls.

I could put together a pull request for this if you are interested in seeing it in action.

Tag current version

Could you please tag the current code base with a version string like 0.1 or similar? That would help using this project in package manager. Thanks.

WebSocket is closed before the connection is established

Hello.
I get this error "WebSocket is closed before the connection is established." when I try to connect and the server is inacessible. The error seems to come from the line:
localWs.close();
when localWs.readyState has the value 0

Is this error normal/unavoidable?

Can't reconnect in FF

Hi - Have you noticed any issues in FF. I'm running FF21. During development, sometimes the browser is disconnected for a while and then it wouldn't reconnect when the server comes up. Error msg that keep repeaing are

Firefox can't establish a connection to the server at <target>
The connection to <target> was interrupted while the page was loading. 

Here is what I have tried so far

  1. Refresh tab (button or Ctrl+F5): No changes. It somehow maintains state. And the above error comes up every couple of seconds
  2. Closing the browser and restarting it: The tabs come back and it can now connect
  3. Debugging: During debug, I can get the connection to go through if I debug with firebug

Any suggestions on where to start?

How to manually reconnect?

Lets say I open a websocket to a site. Soon after, my computer goes to sleep. When waking my computer up, I'm no longer connected to the websocket. But the library obviously doesn't know I need to reconnect since an onclose event never got a chance to run. There doesn't seem to be a way for me to manually reconnect. Also there doesn't seem to be a way to tell if I am actually still connected (not sure if that is even possible).

So in order to reconnect I have to remake the ReconnectingWebsocket AND redefine all my onopen, onmessage, etc functions, which is a bummer. There should just be a .reconnect() or .connect() function that recreates the Websocket inside the library for you so you don't have to redefine everything.

`timeoutInterval` must be set as an option to take effect on the first connection

This example doesn't work with timeoutInterval because it needs to be present when the socket autoconnects the first time.

var socket = new ReconnectingWebSocket(url);
socket.debug = true;
socket.timeoutInterval = 5400;

It's only possible to set the timeoutInterval in the options param. Just wanted to note this since it is the example in the docs. The other options are fine though.

Sockets keeps reconnecting

For as far as i can see the onopen ecvent keeps getting triggered, even if the connection is already succesfully made.

Binary Type of ArrayBuffer does not transfer correctly

I setup the whiteboard project using websockets based on this url: https://blogs.oracle.com/arungupta/entry/collaborative_whiteboard_using_websocket_in

Within the text at this url is the following
"The important part is to set the binaryType property of WebSocket to arraybuffer. This ensures that any binary transfers using WebSocket are done using ArrayBuffer as the default type seems to be blob. "

This binary type will not transfer from one client to another client.
The sending client logs:
sending binary: [object ArrayBuffer]
and the receiving client logs:
received: [object Blob]
This works without using the reconnect classes
Thanks
Tom

Not working in Safari

I tested it in Safari for mac and on iOS 7

Get this error:

Error: Can't find variable: ReconnectingWebSocket

I dont know where to fix since the shitty safari debug tool shows me no hint to the source or the call

Library assumes browser environment

Just running into an issue where the library tries to reference the document in various places (and even tries to create a div). In a mobile environment, this context is not available.

No support IE.

IE don't support addEventListener. IE use attachEvent.

How to fixed?

about cookies

hi:
How to add cookies information to the connection?

Error when loaded via RequireJS

When loaded via RequireJS I get the following error:
ReconnectingWebSocket is not defined

When I commented out if branch which checks for define and define.amd it started work like a charm.

npm install?

Doesn't seem to have shorthand npm version
npm i --save ReconnectingWebSocket
npm i --save reconnecting-websocket
both fails

Can you override open w/o screwing up the library?

I know this isn't an issue or pull request but I don't know where else to ask this question. Sorry.

Normally with my websocket connection I, after a connection is opened, there is various amounts of data that I need to send to the server. I usually do this:

    ws = new WebSocket(url);
    ws.onopen = function()
    {
        ws.send('data to be sent');
    };

That way, I only attempt to send my data after the connection has definitely been made.

However, when I use Reconnecting WebSocket, since it already has the onopen method defined, I assume I shouldn't "redefine" onopen, right? If I can't redefine onopen then what is the best way for me to recognize when the connection has been established so I can do stuff? Use a setInterval() method and check periodically if the connection is made?

Compatibility with node.js

I would like to use this in node (with node-ws) but it implies getting rid of the "browser-only" bits of code like the use of a div as an event emitter and the use of document. This would also fix #51

ReconnectingWebSocket is not defined, Electron app

Hi,
I get an error while running an app in Electron.
This app is running normally in browsers (firefox, chrome, chromium v63.0.3239.132), but not in Electron (chromium v58.0.3029.110)

Electron loads the url of the app in a browser window like a user would do and I get this error at launch:

ReconnectingWebSocket is not defined

Whatever I do (including the lib just before the implementation in the same file) I get this error.

Sending a message upon reconnect

I'm surprised no one has asked for this. I need the ReconnectingWebSocket to send a message to the server when it reconnects, so the server knows what to stream.

Edit: Ah, I think I don't even need this. The ReconnectingWebSocket API sends me an onOpen event upon reconnect. And in the onOpen method, I send the necessary streaming command to the server anyway. It just works as advertised. You can test here if you like.

timeout upon initial connection?

How would I detect and capture a timeout when first attempting to connect, if for example the url was not a active websocket?

One or more reserved bits

I have this trouble from today afternoon. On the other machines, it works... I don't know.

WebSocket connection to 'ws://192.168.0.153:9000/socket_listener_1.php' failed: One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1

reconnecting-websocket.js:209 WebSocket connection to 'ws://192.168.0.101:9000/socket_listener_1.php' failed: One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1

reconnecting-websocket.js:209 WebSocket connection to 'ws://192.168.0.2:9000/socket_listener_1.php' failed: One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1

Firefox 26 does not reconnect after server bounce

This could be browser bug - I'm not sure.
I ran a test using Internet Explorer, Firefox 26, and Chrome. I had all 3 clients working as expected with text messages. I then bounced the server (Glassfish 4). Internet Explorer and Chrome reconnected. Firefox did not. I ran the test twice - same results.

Firefox Log:
The connection to ws://127.0.0.1:8080/ReconnectingWebSocket/websocket was interrupted while the page was loading. reconnecting-websocket.js:84
18:36:40.705 Firefox can't establish a connection to the server at ws://127.0.0.1:8080/ReconnectingWebSocket/websocket. reconnecting-websocket.js:84
18:36:40.705 The connection to ws://127.0.0.1:8080/ReconnectingWebSocket/websocket was interrupted while the page was loading. reconnecting-websocket.js:84
18:36:44.362 Firefox can't establish a connection to the server at ws://127.0.0.1:8080/ReconnectingWebSocket/websocket.

Two websocket per page

Hi, I have some problem with two web socket per page. This code is not working for me:

var fooWs = new ReconnectingWebSocket("ws://" + window.location.host + "/myapp/ws/foo");
var barWs = new ReconnectingWebSocket("ws://" + window.location.host + "/myapp/ws/bar");

fooWs.onopen = function() {
  console.log("fooWs open");
};

fooWs.onclose = function(event) {
  console.log('fooWs close code: ' + event.code + ' reason: ' + event.reason);
};

fooWs.onmessage = function(event) {
  console.log("fooWs onmessage " + event.data);
};

fooWs.onerror = function(error) {
   console.log("fooWs error " + error.message);
};


barWs.onopen = function() {
  console.log("barWs open");
};

barWs.onclose = function(event) {
  console.log('barWs close code: ' + event.code + ' reason: ' + event.reason);
};

barWs.onmessage = function(event) {
  console.log("barWs onmessage " + event.data);
};

barWs.onerror = function(error) {
   console.log("barWs error " + error.message);
};

When run, I have next output:

fooWs open
barWs open
barWs close code: undefined reason: undefined
barWs open
barWs close code: undefined reason: undefined
fooWs onmessage {"test":true}
barWs open
barWs close code: undefined reason: undefined
barWs open
barWs close code: undefined reason: undefined
barWs open
barWs close code: undefined reason: undefined
barWs open
...

Do you have any ideas?

Thank you.

reconnecting-websockets.d.ts does not compile

The reconnecting-websockets.d.ts does not compile anymore after the inclusion of "public maxReconnectAttempts?: number;" into the code.
At least the TS 1.4.1 compiler complains with the following message:
"error TS1112: A class member cannot be declared optional."

Issue on switching from WiFi to Data Plan

It works normally until switching from WiFi to Data Plan, it threw the error form the line:

 throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';

the INVALID_STATE_ERR saying "Still in CONNECTING state." so it paused the reconnecting method.

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.