Synposis
An elegant way to define lightweight protocols on-top of TCP/TLS sockets in node.js
Motivation
Working within node.js it is very easy to write lightweight network protocols that communicate over TCP or TLS. The definition of such protocols often requires repeated (and tedious) parsing of individual TCP/TLS packets into a message header and some JSON body.
Build Status
Installation
[sudo] npm install nssocket
How it works
With nssocket
this tedious bookkeeping work is done automatically for you in two ways:
- Leverages wildcard and namespaced events from EventEmitter2
- Automatically serializes messages passed to
.send()
and deserializes messages fromdata
events. - Implements default reconnect logic for potentially faulty connections.
- Automatically wraps TCP connections with TLS using a known workaround
Messages
Messages in nssocket
are serialized JSON arrays of the following form:
"namespace" "to" "event" "this": "is" "the": "payload"
Although this is not as optimal as other message formats (pure binary, msgpack) most of your applications are probably IO-bound, and not by the computation time needed for serialization / deserialization. When working with NsSocket
instances, all events are namespaced under data
to avoid collision with other events.
Simple Example
var nssocket = ;//// Create an `nssocket` TCP server//var server = nssocket;//// Tell the server to listen on port `6785` and then connect to it// using another NsSocket instance.//server;var outbound = ;outbounddata'you' 'there' {outbound;};outbound;
Reconnect Example
nssocket
exposes simple options for enabling reconnection of the underlying socket. By default, these options are disabled. Lets look at a simple example:
var net =nssocket = ;net;//// Create an NsSocket instance with reconnect enabled//var socket =reconnect: truetype: 'tcp4';socket;socket;
API
socket.send(event, data)
Writes data
to the socket with the specified event
, on the receiving end it will look like: JSON.stringify([event, data])
.
socket.on(event, callback)
Equivalent to the underlying .addListener()
or .on()
function on the underlying socket except that it will permit all EventEmitter2
wildcards and namespaces.
socket.data(event, callback)
Helper function for performing shorthand listeners namespaced under the data
event. For example:
//// These two statements are equivalent//someSocket;someSocketdata'some' 'event' { };
socket.end()
Closes the current socket, emits close
event, possibly also error
socket.destroy()
Remove all listeners, destroys socket, clears buffer. It is recommended that you use socket.end()
.
Tests
All tests are written with vows and should be run through npm:
$ npm test