Lightweight and isomorphic Web Socket lib with socket.io-like event handling, Promise-based requests, and channels.
Much like Socket.io, this library provides a protocol and API that sits on top
of native WebSockets. Rather than passing raw messages through the WebSocket
this library provides an RPC-like API that allows you to pass JSON data over
WebSockets and trigger event handlers on the remote end. There is also a
Promise-based request/response API, as well.
This library is isomorphic, so it can wrap WebSockets on the client (i.e. browser) or on a Node.js server using the ws library. You can get even fancier on the server side and utilize the ws-server-wrapper library (recommended).
Because lightweight is sometimes what you want. This library and its dependencies weigh under 3 KB when minified and gzipped!
This lib might be useful if you want some socket.io functionality (i.e. namespaces, event handling, etc.), but you don't want all of the engine.io transports. When using this library in conjunction with a library like ws, your real-time web application can be pretty darn lightweight without giving up some nice bare-bones functionality.
npm install ws-wrapper
WebSocketWrapper is a CommonJS module, so it works in Node.js and in the browser if you use a bundler like Browserify, Webpack, Parcel.js, or module-concat.
Check out the example-app for a sample chat application (recommended).
Note: This module uses ES6 classes. If you need this to work in IE or another old, decrepit browser, try using a code transpiler like Babel.
Note: This module uses
JSON.stringify to serialize data over the raw WebSocket
connection. This means that serializing circular references is not supported
out of the box.
// Use a bundler to make the next line of code "work" on the browserconst WebSocketWrapper = ;// Create a new socketvar socket = "ws://" + locationhostname ;// Now use the WebSocketWrapper API... `socket.emit` for example// See examples below...
Use ws-server-wrapper to wrap the WebSocketServer (recommended). See ws-server-wrapper README for more details.
If you don't want to use ws-server-wrapper, you can wrap the WebSocket once a new WebSocket connects like this:
const WebSocketServer = ServerWebSocketWrapper = ;var wss = port: 3000;wss;
Other servers (i.e. Go)
No such libraries exist yet. :( Please create one, and let me know about it! I'll give you beer!
It's what you'd expect of an event handler API.
once to bind an event handler to the
wrapper or to a channel.
emit to send an event.
Server-side Example (without using ws-server-wrapper):
const WebSocketServer = ServerWebSocketWrapper = ;var wss = port: 3000;var sockets = ;wss;
// Use a bundler to make the next line of code "work" on the browserconst WebSocketWrapper = ;// Establish connectionvar socket ="ws://" + locationhost;// Add "msg" event handlersocket;// Emit "msg" eventsocket;
Just like in socket.io, you can "namespace" your events using channels. When sending messages to multiple channels, the same WebSocket connection is reused, but the events are logically separated into their appropriate channels.
By default, calling
emit directly on a WebSocketWrapper instance will send
the message over the "default" channel. To send a message over a channel named
"foo", just call
Request / Response
Event handlers can return values or Promises to respond to requests. The response is sent back to the remote end.
The example below shows the client requesting data from the server, but ws-wrapper also allows servers to request data from the client.
Server-side Example (without using ws-server-wrapper):
const fs =WebSocketServer = ServerWebSocketWrapper = ;var wss = port: 3000;var sockets = ;wss;
// Assuming WebSocketWrapper is somehow available to this scope...var socket ="ws://" + locationhost;var p = socket;// `p` is a Promise that will resolve when the server responds...p;socket;
A WebSocketWrapper simply wraps around a WebSocket to give you well-deserved functionality. :)
socket = new WebSocketWrapper(webSocketInstance[, options]);
Constructs a new WebSocketWrapper, and binds it to the native WebSocket instance.
webSocketInstance- the native WebSocket instance
debug- set to
trueto print debugging messages to
errorToJSON- function to serialize Errors over the WebSocket. In Node.js, the default is to send only the
messageproperty of the Error (for security reasons). Errors that occur on the browser include all properties.
requestTimeout- maximum delay in ms. that the WebSocketWrapper will wait until rejecting the Promise of a pending request. Defaults to
null, which means that there will be no timeout. This option is recommended for servers because clients who do not fulfill pending requests can cause memory leaks.
- Event: "open" / "connect"
event- The (worthless) event from the native WebSocket instance
- Event: "error"
event- The Error event from the native WebSocket instance
- Event: "message"
event- The Message event from the native WebSocket instance
data- The message data (same as
- Event: "close" / "disconnect"
event- The Close event from the native WebSocket instance
trueif the "open" event was fired on the native WebSocket instance before the "close" event was fired.
Note: The "special" events listed above are not sent over the WebSocket.
The EventEmitter-like API looks like this:
socket.on(eventName, listener)Adds the
listenerfunction to the end of the listeners array for the event named
eventName. When an event or request matching the
eventNameis received by the WebSocket, the
Values returned by the
listenercallback are used to respond to requests (see
socket.request). If the return value of the
Promise, the response to the request will be sent once the Promise is resolved or rejected; otherwise, the return value of the
listeneris sent back to the remote end immediately.
If the inbound message is a simple event (see
socket.emit), the return value of the
listeneris ignored. It is also "safe" for the
listenerto return a
Promiseeven if the inbound message is a "simple" event. If the returned
Promiseis rejected, an unhandled rejection will not occur; rather, the result of the Promise is just ignored.
listenerthrows an Error, this Error will propagate up the stack as expected, and if the inbound message was a request, the Error is sent back to the remote end as a response rejection.
socket.once(eventName, listener)Adds a one time
listenerfunction for the event named
socket.removeListener(eventName, listener)Removes the specified
listenerfrom the listener array for the event named
socket.removeAllListeners([eventName])Removes all listeners, or those of the specified
socket.eventNames()Returns an array listing the events for which the emitter has registered listeners.
socket.listeners(eventName)Returns a copy of the array of listeners for the event named
socket.emit(eventName[, ...args])Sends an event down the WebSocket with the specified
eventNamecalling all listeners for
eventNameon the remote end, in the order they were registered, passing the supplied arguments to each.
socket.request(eventName[, ...args])Sends a request down the WebSocket with the specified
eventNameand returns a Promise that will resolve once the remote event listener responds.
Note: While it is common design for only one event listener to exist on the remote end, all listeners for
eventNameon the remote end are called, in the order they were registered, passing the supplied arguments to each. Since Promises can only be resolved or rejected once, only the data from the first event listener is used to generate the response for this request.
Note: If a request is sent, but there is no remote event listener to respond to the request, a response rejection is immediately sent back by the remote end.
socket.timeout(tempTimeoutInMs)Temporarily sets the
tempTimeoutInMsfor the next request only. This returns
socketto allow chaining. Typical usage:// The next request will be rejected if there is no response for 5 secs.let promise = socket;
The above EventEmitter functions like
once are chainable (as
socket.of(channelName)Returns the channel with the specified
channelName. Every channel has the same EventEmitter-like API as described above for sending and handling channel-specific events and requests. A channel also has a read-only
Other methods and properties:
By default, the WebSocketWrapper provides a queue for data to be sent. Once the WebSocket is open, this queue is flushed until the connection is lost. The following methods allow one to re-bind a new WebSocket or clear the send queue.
socket.abort()Clears the send queue for this WebSocketWrapper and rejects all Promises for pending requests.
socket.bind(nativeWebSocket)Binds this WebSocketWrapper to a new WebSocket. This can be useful when socket reconnection logic needs to be implemented. Instead of creating a new WebSocketWrapper each time a WebSocket is disconnected, one can simply bind a new WebSocket to the WebSocketWrapper. In this way, data queued to be sent while the connection was dead will be sent over the new WebSocket passed to the
socket.isConnecting- checks the native WebSocket
trueif and only if the state is CONNECTING.
socket.isConnected- checks the native WebSocket
trueif and only if the state is CONNECTED.
socket.send(data)If connected, calls the native WebSocket's
sendmethod; otherwise, the data is added to the WebSocketWrapper's send queue.
socket.disconnect()Closes the native WebSocket
socket.set(key, value)Saves user data specific to this WebSocketWrapper
socket.get(key)Retrieves user data. See
The maximum number of items allowed in the send queue. If a user tries to
send more messages than this number while a WebSocket is not connected,
errors will be thrown. Defaults to 10; changes affect all WebSocketWrapper
All data passed over the native WebSocket should be valid JSON, but this is not a hard requirement. ws-wrapper will try to parse a JSON string and determine the message type based on the properties in the parsed Object.
The following message types are defined by ws-wrapper:
Event Dispatch - Identified by an Object with
akey but no
ikey. The channel name is optional."c": "channel_name""a": "event_name" "first_arg" "second_arg" "last_arg"
The client or server can send events. Events are nothing more than an event name and some data, passed as arguments to the event handler.
Request - Identified by an Object with
irefers to the unique request identifier. The channel name is optional."i": 123"c": "channel_name""a": "event_name" "first_arg" "second_arg" "last_arg"
The client or server can send a Request, which is essentially an Event that needs some sort of server Response.
Response (Resolution) - Identified by an Object with
iis the request identifier and
dis the response data."i": 123"d": "resolved": "data" "hello": "world"
Response (Rejection) - Identified by an Object with
iis the request identifier and
eis the error Object to be used when rejecting the response Promise. If
_is set, the
eObject is converted into an Error instance upon receipt."i": 123"e": "message": "error message""_": 1
If the message received by the WebSocket is not valid JSON or if the parsed
Object does not match one of the above message types, then the message is
simply ignored by ws-wrapper. Also if the JSON message contains a
property with the value
false, the message will be ignored. This allows
other libraries to use the same WebSocket and send messages that will not be
processed by ws-wrapper.
ws-wrapper does not implement auto-reconnect functionality out of the box. For those who want it (almost everyone), I have written some sample code to show how easy it is to add.
If someone wants to make an npm package for the auto-reconnect feature, I'd be happy to list it here, but it will probably never be a core ws-wrapper feature.