7.0.0 • Published 2 years ago

pws v7.0.0

Weekly downloads
579
License
WTFPL
Repository
github
Last release
2 years ago

NPM version Size license

🤝 PWS - PersistentWebSocket

PWS gives you a reconnecting websocket to use in the browser or in node simply by switching out new WebSocket with new PersistentWebSocket.

It behaves the same as a regular browser WebSocket, but reconnects automatically with a simple backoff algorithm if the connection closes.

Getting started

const pws = new PersistentWebSocket(url)

// Called every time a connection is established
pws.onopen = () => pws.send('Hello')

// Echo messages received
pws.onmessage = event => pws.send('You said: ' + event.data)

More details at https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket

Using in node

You can also use PWS with the nodejs WebSocket library ws

const WebSocket = require('ws')
    , Pws = require('pws')

const pws = Pws(url, WebSocket)

// as in the browser...

More details at https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketaddress-protocols-options

Heartbeat

To ensure a persistent connection it's necessary to send messages at regular intervals from the server to keep the connection alive. The WebSocket protocol only implements a ping to be sent from the server, but not in the other direction. This can leave the client in a half open state where it thinks it's connected, but doesn't receive messages from the server. To prevent this state PWS let's you set a specific timeout after which to force a reconnection if you did not receive any messages from the server.

new PersistentWebSocket(url, {
  pingTimeout: 30 * 1000 // Reconnect if no message received in 30s.
})

Backoff algorithm

The backoff algorithm is inspired by primus and http://dthain.blogspot.com/2009/02/exponential-backoff-in-distributed.html, and stops at a maximum reconnection timeout of 5 minutes.

Reconnect on browser online

PWS will also reconnect on the browsers online event, irregardless of the current timeout for the next reconnect, to ensure a connection is regained as fast as possible.

6.0.1

2 years ago

7.0.0

2 years ago

6.0.0

2 years ago

5.0.2

4 years ago

5.0.1

4 years ago

5.0.0

4 years ago

5.0.0-beta.1

4 years ago

4.3.0

4 years ago

4.2.0

4 years ago

4.1.2

5 years ago

4.1.1

5 years ago

4.1.0

5 years ago

4.0.6

5 years ago

4.0.5

5 years ago

4.0.4

5 years ago

4.0.3

5 years ago

4.0.2

5 years ago

4.0.1

5 years ago

4.0.0

5 years ago

3.0.3

5 years ago

3.0.2

5 years ago

3.0.1

5 years ago

2.0.3

5 years ago

3.0.0

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

2.0.0-alpha2

5 years ago

2.0.0-alpha

5 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.4.0

7 years ago

0.3.1

7 years ago

0.3.0

7 years ago

0.2.2

7 years ago

0.2.1

7 years ago

0.2.0

7 years ago

0.1.0

7 years ago