Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

semicalypse

  • Loading branch information...
commit 9e44b5bcbe208082247aa8567d04214a6c80bf77 1 parent bc27b5c
@kilianc authored
View
18 examples/bla.js
@@ -1,15 +1,15 @@
-var nss = require('../')
+var nss = require('../');
-var sockets = []
+var sockets = [];
nss.createServer(function (socket) {
- sockets.push(socket)
+ sockets.push(socket);
socket.ondata('connecting', function (data) {
- console.log('There are now', sockets.length)
+ console.log('There are now', sockets.length);
sockets.forEach(function (s) {
if (socket !== socket) {
- s.send('broadcasting', data)
+ s.send('broadcasting', data);
}
- })
- console.dir(data)
- })
-}).listen(4949)
+ });
+ console.dir(data);
+ });
+}).listen(4949);
View
10 examples/foo.js
@@ -1,8 +1,8 @@
-var nss = require('../')
-var outbound = nss()
+var nss = require('../');
+var outbound = nss();
outbound.on('data::broadcasting', function (data) {
- console.log(data)
+ console.log(data);
}).connect(4949, function () {
- outbound.send('connecting', { 'random' : Math.random() })
-})
+ outbound.send('connecting', { 'random' : Math.random() });
+});
View
12 examples/reconnect.js
@@ -1,12 +1,12 @@
var net = require('net'),
- nss = require('../')
+ nss = require('../');
net.createServer(function (socket) {
setTimeout(function () {
- socket.destroy()
- }, 1000)
-}).listen(8345)
+ socket.destroy();
+ }, 1000);
+}).listen(8345);
nss.createClient({ reconnect: true }).on('start', function () {
- console.log('start')
-}).connect(8345)
+}).connect(8345);
View
24 examples/simple-protocol.js
@@ -1,10 +1,10 @@
-var nss = require('../')
+var nss = require('../');
//
// define a simple message protocol as [<type>, <id>] and create some messages that use it.
//
-var message1 = ['message', 'one']
-var message2 = ['message', 'two']
+var message1 = ['message', 'one'];
+var message2 = ['message', 'two'];
//
// Create an `nss` TCP server and tell the server to listen on port `6785`.
@@ -15,7 +15,7 @@ var server = nss.createServer(function (socket) {
// Here `socket` will be an instance of `NsSocket`.
// When there is a connection, send `message1` to the socket.
//
- socket.send(message1)
+ socket.send(message1);
//
// listen for `message2` from the connecting socket.
@@ -27,25 +27,25 @@ var server = nss.createServer(function (socket) {
// speaks our language, we will likely be provided with
// a payload. In this case `{ "foo": "bar" }`.
//
- console.log(data)
- })
+ console.log(data);
+ });
-}).listen(6785)
+}).listen(6785);
//
// Create a new `NsSocket` instance and then connect to the server in 1000 miliseconds.
//
setTimeout(function() {
- var outbound = nss()
+ var outbound = nss();
//
//
//
outbound.ondata(message1, function () {
- outbound.send(message2, { "foo": "bar" })
- })
+ outbound.send(message2, { "foo": "bar" });
+ });
- outbound.connect(6785)
+ outbound.connect(6785);
-}, 1000)
+}, 1000);
View
58 examples/verbose-protocol.js
@@ -1,34 +1,34 @@
- var nss = require('../')
+var nss = require('../');
- //
- // Create an `nss` TCP server
- //
- var server = nss.createServer(function (socket) {
- //
- // Here `socket` will be an instance of `NsSocket`.
- //
+//
+// Create an `nss` TCP server
+//
+var server = nss.createServer(function (socket) {
+ //
+ // Here `socket` will be an instance of `NsSocket`.
+ //
- socket.send(['drink', 'rum'])
- socket.send(['drink', 'vodka'])
+ socket.send(['drink', 'rum']);
+ socket.send(['drink', 'vodka']);
- // socket.data(['iam', 'here'], function (data) {
- // //
- // // Good! The socket speaks our language
- // // (i.e. simple 'you::there', 'iam::here' protocol)
- // //
- // // { iam: true, indeedHere: true }
- // //
- // console.dir(data)
- // })
- })
+ // socket.data(['iam', 'here'], function (data) {
+ // //
+ // // Good! The socket speaks our language
+ // // (i.e. simple 'you::there', 'iam::here' protocol)
+ // //
+ // // { iam: true, indeedHere: true }
+ // //
+ // console.dir(data)
+ // })
+});
- //
- // Tell the server to listen on port `6785` and then connect to it
- // using another NsSocket instance.
- //
- server.listen(6785)
+//
+// Tell the server to listen on port `6785` and then connect to it
+// using another NsSocket instance.
+//
+server.listen(6785);
- nss().ondata(['drink', '*'], function () {
- console.log('I can mix a', this.event[2], 'drink')
- //outbound.send(['iam', 'here'], { iam: true, indeedHere: true })
- }).connect(6785)
+ console.log('I can mix a', this.event[2], 'drink');
+ //outbound.send(['iam', 'here'], { iam: true, indeedHere: true })
+}).connect(6785);
View
2  index.js
@@ -1,3 +1,3 @@
module.exports = process.env.NSSOCKET_COV
? require('./lib-cov/nssocket')
- : require('./lib/nssocket')
View
2  lib-cov/nssocket.js
@@ -532,4 +532,4 @@ function configureEvents(self) {
self.timeout && self.socket.setTimeout(this.timeout);
}));
}
-_$jscoverage['nssocket.js'].source = ["var net = require('net'),"," tls = require('tls'),"," util = require('util'),"," assert = require('chai').assert,"," EventEmitter2 = require('eventemitter2').EventEmitter2,"," bufferjoiner = require('bufferjoiner')","","module.exports = NsSocket","","module.exports.createClient = NsSocket","","module.exports.createServer = function createServer(options, connectionListener) {"," if (!connectionListener &amp;&amp; typeof options === 'function') {"," connectionListener = options"," options = {}"," }",""," options.type = options.type || 'tcp4'"," options.delimiter = options.delimiter || '::'",""," function onConnection (socket) {"," // inbounds sockets can not reconnect by definition"," options.reconnect = false"," connectionListener(new NsSocket(options, socket))"," }",""," return options.type === 'tls'"," ? tls.createServer(options, onConnection)"," : net.createServer(options, onConnection)","}","","// retro compatibility fixes","module.exports.data = module.exports.ondata","module.exports.unData = module.exports.offdata","module.exports.dataOnce = module.exports.oncedata","","function NsSocket(options, socket) {"," if (!(this instanceof NsSocket)) {"," return new NsSocket(options, socket)"," }",""," if (!options) {"," options = socket || {}"," }",""," this.connected = false"," this.type = options.type || 'tcp4'"," this.retry = options.reconnect ? {"," retries: 0,"," max: options.maxRetries || 10,"," wait: options.retryInterval || 5000,"," timeoutId: undefined"," } : false",""," EventEmitter2.call(this, {"," delimiter: options.delimiter || '::',"," wildcard: true,"," maxListeners: options.maxListeners || 10"," })",""," if (socket) {"," this.stream = socket"," this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket"," this.connected = this.socket.writable &amp;&amp; this.socket.readable || false"," configureEvents(this)"," }","}","","util.inherits(NsSocket, EventEmitter2)","","NsSocket.prototype.connect = function connect(port) {"," this.retry.timeoutId &amp;&amp; clearTimeout(this.retry.timeoutId)",""," if (!this.socket) {"," var module = this.type === 'tls' ? tls : net",""," this.stream = module.connect.apply(null, arguments)"," this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket"," this.connected = this.socket.writable &amp;&amp; this.socket.readable || false"," this.connectionArgs = arguments",""," configureEvents(this)"," } else {"," this.socket.connect.apply(this.socket, arguments)"," }"," return this","}","","NsSocket.prototype.write = function write(buff) {"," // if we aren't connected/socketed, then error"," if (!this.socket || !this.connected) {"," return this.emit('error', new Error('NsSocket: sending on a bad socket'))"," }"," this.stream.write(buff)"," return this","}","","NsSocket.prototype.send = function send(event, data, callback) {"," // if we aren't connected/socketed, then error"," if (!this.socket || !this.connected) {"," return this.emit('error', new Error('NsSocket: sending on a bad socket'))"," }",""," var dataType = typeof data"," if (dataType === 'undefined' || dataType === 'function') {"," callback = data"," data = null"," }",""," this.stream.write(this.createMessage(event, data), callback)"," return this","}","","NsSocket.prototype.createMessage = function createMessage(event, data) {"," var header = new Buffer(9)",""," if (typeof event === 'string') {"," event = event.split(this.delimiter)"," }",""," event = Buffer(JSON.stringify(event))",""," if (Buffer.isBuffer(data)) {"," header.writeInt8(1, 8)"," } else {"," data = Buffer(JSON.stringify(data))"," header.writeInt8(0, 8)"," }",""," header.writeUInt32BE(event.length, 0)"," header.writeUInt32BE(data.length, 4)",""," return Buffer.concat([header, event, data], 9 + event.length + data.length)","}","","NsSocket.prototype.ondata = function (event, listener) {"," if (typeof event === 'string') {"," event = event.split(this.delimiter)"," }"," return this.on(['data'].concat(event), listener)","}","","NsSocket.prototype.offdata = function (event, listener) {"," return this.off(['data'].concat(event), listener)","}","","NsSocket.prototype.oncedata = function (event, listener) {"," if (typeof event === 'string') {"," event = event.split(this.delimiter)"," }"," return this.once(['data'].concat(event), listener)","}","","NsSocket.prototype.setIdle = function setIdle(timeout) {"," this.socket.setTimeout(timeout)"," this.timeout = timeout","}","","NsSocket.prototype.destroy = function destroy() {"," this.removeAllListeners()",""," try {"," this.socket.end()"," this.socket.destroy()"," } catch (err) {}",""," this.emit('destroy')","}","","NsSocket.prototype.end = function end() {"," var hadErr"," this.connected = false",""," try {"," this.socket.end()"," } catch (err) {"," hadErr = true"," this.emit('error', err)"," }",""," this.emit('close', hadErr)","}","","NsSocket.prototype.reconnect = function reconnect() {"," var self = this",""," this.retry.timeoutId = setTimeout(function tryReconnect() {"," self.retry.retries ++",""," if (self.retry.retries &gt;= self.retry.max) {"," return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max))"," }",""," self.retry.waiting = true",""," // here for debugging reasons"," assert.isFalse(self.connected, 'before actually reconnect connected must be false')"," assert.isUndefined(self.socket, 'before actually reconnect socket must be destroied')",""," self.once('start', function () {"," self.retry.waiting = false"," self.retry.retries = 0"," })",""," self.connect.apply(self, self.connectionArgs)"," }, this.retry.wait)","}","","function configureEvents(self) {"," // parsing holders"," var eventLength = -1"," var messageLength = -1"," var messagetype = 0"," var bufferJoiner = bufferjoiner()",""," if (self.type === 'tls') {"," self.stream.on('secureConnect', onStart)"," } else {"," self.socket.on('connect', onStart)"," }",""," function onStart() {"," self.connected = true"," self.emit('start')"," }",""," self.stream.on('data', function onData(chunk) {"," ~messageLength"," ? fetchBody(chunk)"," : fetchHeader(chunk)"," })",""," function fetchHeader(chunk) {"," if (bufferJoiner.length + chunk.length &gt;= 9) {"," var header = bufferJoiner.add(chunk).join()"," eventLength = header.readUInt32BE(0)"," messageLength = header.readUInt32BE(4)"," messagetype = header.readInt8(8)"," fetchBody(chunk.slice(9))"," } else {"," bufferJoiner.add(chunk)"," }"," }",""," function fetchBody(chunk) {"," var raw, event, data"," var chunkLength = chunk.length"," var bytesLeft = (eventLength + messageLength) - bufferJoiner.length",""," if (chunkLength &gt;= bytesLeft) {"," raw = bufferJoiner.add(chunk.slice(0, bytesLeft)).join()"," event = JSON.parse(raw.slice(0, eventLength))"," data = messagetype ? raw.slice(eventLength) : JSON.parse(raw.slice(eventLength).toString())",""," eventLength = -1"," messageLength = -1",""," self.emit(['data'].concat(event), data)",""," if (chunkLength - bytesLeft) {"," fetchHeader(chunk.slice(bytesLeft))"," }",""," return"," }",""," bufferJoiner.add(chunk)"," }",""," self.socket.on('close', function onClose(hadError) {"," self.socket.destroy()"," self.socket = undefined"," self.connected = false",""," if (hadError) {"," self.emit('close', hadError, arguments[1])"," } else {"," self.emit('close')"," }",""," self.retry &amp;&amp; self.reconnect()"," })",""," self.socket.on('error', function (err) {"," !self.retry &amp;&amp; self.emit('error', err || new Error('An Unknown Error occured'))"," })",""," self.socket.on('timeout', function onIdle() {"," self.emit('idle')"," self.timeout &amp;&amp; self.socket.setTimeout(this.timeout)"," })","}"];
+_$jscoverage['nssocket.js'].source = ["var net = require('net'),"," tls = require('tls'),"," util = require('util'),"," assert = require('chai').assert,"," EventEmitter2 = require('eventemitter2').EventEmitter2,"," bufferjoiner = require('bufferjoiner');","","module.exports = NsSocket;","","module.exports.createClient = NsSocket;","","module.exports.createServer = function createServer(options, connectionListener) {"," if (!connectionListener &amp;&amp; typeof options === 'function') {"," connectionListener = options;"," options = {};"," }",""," options.type = options.type || 'tcp4';"," options.delimiter = options.delimiter || '::';",""," function onConnection (socket) {"," // inbounds sockets can not reconnect by definition"," options.reconnect = false;"," connectionListener(new NsSocket(options, socket));"," }",""," return options.type === 'tls'"," ? tls.createServer(options, onConnection)"," : net.createServer(options, onConnection);","};","","// retro compatibility fixes","module.exports.data = module.exports.ondata;","module.exports.unData = module.exports.offdata;","module.exports.dataOnce = module.exports.oncedata;","","function NsSocket(options, socket) {"," if (!(this instanceof NsSocket)) {"," return new NsSocket(options, socket);"," }",""," if (!options) {"," options = socket || {};"," }",""," this.connected = false;"," this.type = options.type || 'tcp4';"," this.retry = options.reconnect ? {"," retries: 0,"," max: options.maxRetries || 10,"," wait: options.retryInterval || 5000,"," timeoutId: undefined"," } : false;",""," EventEmitter2.call(this, {"," delimiter: options.delimiter || '::',"," wildcard: true,"," maxListeners: options.maxListeners || 10"," });",""," if (socket) {"," this.stream = socket;"," this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket;"," this.connected = this.socket.writable &amp;&amp; this.socket.readable || false;"," configureEvents(this);"," }","}","","util.inherits(NsSocket, EventEmitter2);","","NsSocket.prototype.connect = function connect(port) {"," this.retry.timeoutId &amp;&amp; clearTimeout(this.retry.timeoutId);",""," if (!this.socket) {"," var module = this.type === 'tls' ? tls : net;",""," this.stream = module.connect.apply(null, arguments);"," this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket;"," this.connected = this.socket.writable &amp;&amp; this.socket.readable || false;"," this.connectionArgs = arguments;",""," configureEvents(this);"," } else {"," this.socket.connect.apply(this.socket, arguments);"," }"," return this;","};","","NsSocket.prototype.write = function write(buff) {"," // if we aren't connected/socketed, then error"," if (!this.socket || !this.connected) {"," return this.emit('error', new Error('NsSocket: sending on a bad socket'));"," }"," this.stream.write(buff);"," return this;","};","","NsSocket.prototype.send = function send(event, data, callback) {"," // if we aren't connected/socketed, then error"," if (!this.socket || !this.connected) {"," return this.emit('error', new Error('NsSocket: sending on a bad socket'));"," }",""," var dataType = typeof data;"," if (dataType === 'undefined' || dataType === 'function') {"," callback = data;"," data = null;"," }",""," this.stream.write(this.createMessage(event, data), callback);"," return this;","};","","NsSocket.prototype.createMessage = function createMessage(event, data) {"," var header = new Buffer(9);",""," if (typeof event === 'string') {"," event = event.split(this.delimiter);"," }",""," event = Buffer(JSON.stringify(event));",""," if (Buffer.isBuffer(data)) {"," header.writeInt8(1, 8);"," } else {"," data = Buffer(JSON.stringify(data));"," header.writeInt8(0, 8);"," }",""," header.writeUInt32BE(event.length, 0);"," header.writeUInt32BE(data.length, 4);",""," return Buffer.concat([header, event, data], 9 + event.length + data.length);","};","","NsSocket.prototype.ondata = function (event, listener) {"," if (typeof event === 'string') {"," event = event.split(this.delimiter);"," }"," return this.on(['data'].concat(event), listener);","};","","NsSocket.prototype.offdata = function (event, listener) {"," return this.off(['data'].concat(event), listener);","};","","NsSocket.prototype.oncedata = function (event, listener) {"," if (typeof event === 'string') {"," event = event.split(this.delimiter);"," }"," return this.once(['data'].concat(event), listener);","};","","NsSocket.prototype.setIdle = function setIdle(timeout) {"," this.socket.setTimeout(timeout);"," this.timeout = timeout;","};","","NsSocket.prototype.destroy = function destroy() {"," this.removeAllListeners();",""," try {"," this.socket.end();"," this.socket.destroy();"," } catch (err) {}",""," this.emit('destroy');","};","","NsSocket.prototype.end = function end() {"," var hadErr;"," this.connected = false;",""," try {"," this.socket.end();"," } catch (err) {"," hadErr = true;"," this.emit('error', err);"," }",""," this.emit('close', hadErr);","};","","NsSocket.prototype.reconnect = function reconnect() {"," var self = this;",""," this.retry.timeoutId = setTimeout(function tryReconnect() {"," self.retry.retries ++;",""," if (self.retry.retries &gt;= self.retry.max) {"," return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max));"," }",""," self.retry.waiting = true;",""," // here for debugging reasons"," assert.isFalse(self.connected, 'before actually reconnect connected must be false');"," assert.isUndefined(self.socket, 'before actually reconnect socket must be destroied');",""," self.once('start', function () {"," self.retry.waiting = false;"," self.retry.retries = 0;"," });",""," self.connect.apply(self, self.connectionArgs);"," }, this.retry.wait);","};","","function configureEvents(self) {"," // parsing holders"," var eventLength = -1;"," var messageLength = -1;"," var messagetype = 0;"," var bufferJoiner = bufferjoiner();",""," if (self.type === 'tls') {"," self.stream.on('secureConnect', onStart);"," } else {"," self.socket.on('connect', onStart);"," }",""," function onStart() {"," self.connected = true;"," self.emit('start');"," }",""," self.stream.on('data', function onData(chunk) {"," ~messageLength"," ? fetchBody(chunk)"," : fetchHeader(chunk);"," });",""," function fetchHeader(chunk) {"," if (bufferJoiner.length + chunk.length &gt;= 9) {"," var header = bufferJoiner.add(chunk).join();"," eventLength = header.readUInt32BE(0);"," messageLength = header.readUInt32BE(4);"," messagetype = header.readInt8(8);"," fetchBody(chunk.slice(9));"," } else {"," bufferJoiner.add(chunk);"," }"," }",""," function fetchBody(chunk) {"," var raw, event, data;"," var chunkLength = chunk.length;"," var bytesLeft = (eventLength + messageLength) - bufferJoiner.length;",""," if (chunkLength &gt;= bytesLeft) {"," raw = bufferJoiner.add(chunk.slice(0, bytesLeft)).join();"," event = JSON.parse(raw.slice(0, eventLength));"," data = messagetype ? raw.slice(eventLength) : JSON.parse(raw.slice(eventLength).toString());",""," eventLength = -1;"," messageLength = -1;",""," self.emit(['data'].concat(event), data);",""," if (chunkLength - bytesLeft) {"," fetchHeader(chunk.slice(bytesLeft));"," }",""," return;"," }",""," bufferJoiner.add(chunk);"," }",""," self.socket.on('close', function onClose(hadError) {"," self.socket.destroy();"," self.socket = undefined;"," self.connected = false;",""," if (hadError) {"," self.emit('close', hadError, arguments[1]);"," } else {"," self.emit('close');"," }",""," self.retry &amp;&amp; self.reconnect();"," });",""," self.socket.on('error', function (err) {"," !self.retry &amp;&amp; self.emit('error', err || new Error('An Unknown Error occured'));"," });",""," self.socket.on('timeout', function onIdle() {"," self.emit('idle');"," self.timeout &amp;&amp; self.socket.setTimeout(this.timeout);"," });","}"];
View
262 lib/nssocket.js
@@ -3,290 +3,290 @@ var net = require('net'),
util = require('util'),
assert = require('chai').assert,
EventEmitter2 = require('eventemitter2').EventEmitter2,
- bufferjoiner = require('bufferjoiner')
+ bufferjoiner = require('bufferjoiner');
-module.exports = NsSocket
+module.exports = NsSocket;
-module.exports.createClient = NsSocket
+module.exports.createClient = NsSocket;
module.exports.createServer = function createServer(options, connectionListener) {
if (!connectionListener && typeof options === 'function') {
- connectionListener = options
- options = {}
+ connectionListener = options;
+ options = {};
}
- options.type = options.type || 'tcp4'
- options.delimiter = options.delimiter || '::'
+ options.type = options.type || 'tcp4';
+ options.delimiter = options.delimiter || '::';
function onConnection (socket) {
// inbounds sockets can not reconnect by definition
- options.reconnect = false
- connectionListener(new NsSocket(options, socket))
+ options.reconnect = false;
+ connectionListener(new NsSocket(options, socket));
}
return options.type === 'tls'
? tls.createServer(options, onConnection)
- : net.createServer(options, onConnection)
-}
+ : net.createServer(options, onConnection);
+};
// retro compatibility fixes
-module.exports.data = module.exports.ondata
-module.exports.unData = module.exports.offdata
-module.exports.dataOnce = module.exports.oncedata
+module.exports.data = module.exports.ondata;
+module.exports.unData = module.exports.offdata;
+module.exports.dataOnce = module.exports.oncedata;
function NsSocket(options, socket) {
if (!(this instanceof NsSocket)) {
- return new NsSocket(options, socket)
+ return new NsSocket(options, socket);
}
if (!options) {
- options = socket || {}
+ options = socket || {};
}
- this.connected = false
- this.type = options.type || 'tcp4'
+ this.connected = false;
+ this.type = options.type || 'tcp4';
this.retry = options.reconnect ? {
retries: 0,
max: options.maxRetries || 10,
wait: options.retryInterval || 5000,
timeoutId: undefined
- } : false
+ } : false;
EventEmitter2.call(this, {
delimiter: options.delimiter || '::',
wildcard: true,
maxListeners: options.maxListeners || 10
- })
+ });
if (socket) {
- this.stream = socket
- this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket
- this.connected = this.socket.writable && this.socket.readable || false
- configureEvents(this)
+ this.stream = socket;
+ this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket;
+ this.connected = this.socket.writable && this.socket.readable || false;
+ configureEvents(this);
}
}
-util.inherits(NsSocket, EventEmitter2)
+util.inherits(NsSocket, EventEmitter2);
NsSocket.prototype.connect = function connect(port) {
- this.retry.timeoutId && clearTimeout(this.retry.timeoutId)
+ this.retry.timeoutId && clearTimeout(this.retry.timeoutId);
if (!this.socket) {
- var module = this.type === 'tls' ? tls : net
+ var module = this.type === 'tls' ? tls : net;
- this.stream = module.connect.apply(null, arguments)
- this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket
- this.connected = this.socket.writable && this.socket.readable || false
- this.connectionArgs = arguments
+ this.stream = module.connect.apply(null, arguments);
+ this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket;
+ this.connected = this.socket.writable && this.socket.readable || false;
+ this.connectionArgs = arguments;
- configureEvents(this)
+ configureEvents(this);
} else {
- this.socket.connect.apply(this.socket, arguments)
+ this.socket.connect.apply(this.socket, arguments);
}
- return this
-}
+ return this;
+};
NsSocket.prototype.write = function write(buff) {
// if we aren't connected/socketed, then error
if (!this.socket || !this.connected) {
- return this.emit('error', new Error('NsSocket: sending on a bad socket'))
+ return this.emit('error', new Error('NsSocket: sending on a bad socket'));
}
- this.stream.write(buff)
- return this
-}
+ this.stream.write(buff);
+ return this;
+};
NsSocket.prototype.send = function send(event, data, callback) {
// if we aren't connected/socketed, then error
if (!this.socket || !this.connected) {
- return this.emit('error', new Error('NsSocket: sending on a bad socket'))
+ return this.emit('error', new Error('NsSocket: sending on a bad socket'));
}
- var dataType = typeof data
+ var dataType = typeof data;
if (dataType === 'undefined' || dataType === 'function') {
- callback = data
- data = null
+ callback = data;
+ data = null;
}
- this.stream.write(this.createMessage(event, data), callback)
- return this
-}
+ this.stream.write(this.createMessage(event, data), callback);
+ return this;
+};
NsSocket.prototype.createMessage = function createMessage(event, data) {
- var header = new Buffer(9)
+ var header = new Buffer(9);
if (typeof event === 'string') {
- event = event.split(this.delimiter)
+ event = event.split(this.delimiter);
}
- event = Buffer(JSON.stringify(event))
+ event = Buffer(JSON.stringify(event));
if (Buffer.isBuffer(data)) {
- header.writeInt8(1, 8)
+ header.writeInt8(1, 8);
} else {
- data = Buffer(JSON.stringify(data))
- header.writeInt8(0, 8)
+ data = Buffer(JSON.stringify(data));
+ header.writeInt8(0, 8);
}
- header.writeUInt32BE(event.length, 0)
- header.writeUInt32BE(data.length, 4)
+ header.writeUInt32BE(event.length, 0);
+ header.writeUInt32BE(data.length, 4);
- return Buffer.concat([header, event, data], 9 + event.length + data.length)
-}
+ return Buffer.concat([header, event, data], 9 + event.length + data.length);
+};
NsSocket.prototype.ondata = function (event, listener) {
if (typeof event === 'string') {
- event = event.split(this.delimiter)
+ event = event.split(this.delimiter);
}
- return this.on(['data'].concat(event), listener)
-}
+ return this.on(['data'].concat(event), listener);
+};
NsSocket.prototype.offdata = function (event, listener) {
- return this.off(['data'].concat(event), listener)
-}
+ return this.off(['data'].concat(event), listener);
+};
NsSocket.prototype.oncedata = function (event, listener) {
if (typeof event === 'string') {
- event = event.split(this.delimiter)
+ event = event.split(this.delimiter);
}
- return this.once(['data'].concat(event), listener)
-}
+ return this.once(['data'].concat(event), listener);
+};
NsSocket.prototype.setIdle = function setIdle(timeout) {
- this.socket.setTimeout(timeout)
- this.timeout = timeout
-}
+ this.socket.setTimeout(timeout);
+ this.timeout = timeout;
+};
NsSocket.prototype.destroy = function destroy() {
- this.removeAllListeners()
+ this.removeAllListeners();
try {
- this.socket.end()
- this.socket.destroy()
+ this.socket.end();
+ this.socket.destroy();
} catch (err) {}
- this.emit('destroy')
-}
+ this.emit('destroy');
+};
NsSocket.prototype.end = function end() {
- var hadErr
- this.connected = false
+ var hadErr;
+ this.connected = false;
try {
- this.socket.end()
+ this.socket.end();
} catch (err) {
- hadErr = true
- this.emit('error', err)
+ hadErr = true;
+ this.emit('error', err);
}
- this.emit('close', hadErr)
-}
+ this.emit('close', hadErr);
+};
NsSocket.prototype.reconnect = function reconnect() {
- var self = this
+ var self = this;
this.retry.timeoutId = setTimeout(function tryReconnect() {
- self.retry.retries ++
+ self.retry.retries ++;
if (self.retry.retries >= self.retry.max) {
- return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max))
+ return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max));
}
- self.retry.waiting = true
+ self.retry.waiting = true;
// here for debugging reasons
- assert.isFalse(self.connected, 'before actually reconnect connected must be false')
- assert.isUndefined(self.socket, 'before actually reconnect socket must be destroied')
+ assert.isFalse(self.connected, 'before actually reconnect connected must be false');
+ assert.isUndefined(self.socket, 'before actually reconnect socket must be destroied');
self.once('start', function () {
- self.retry.waiting = false
- self.retry.retries = 0
- })
+ self.retry.waiting = false;
+ self.retry.retries = 0;
+ });
- self.connect.apply(self, self.connectionArgs)
- }, this.retry.wait)
-}
+ self.connect.apply(self, self.connectionArgs);
+ }, this.retry.wait);
+};
function configureEvents(self) {
// parsing holders
- var eventLength = -1
- var messageLength = -1
- var messagetype = 0
- var bufferJoiner = bufferjoiner()
+ var eventLength = -1;
+ var messageLength = -1;
+ var messagetype = 0;
+ var bufferJoiner = bufferjoiner();
if (self.type === 'tls') {
- self.stream.on('secureConnect', onStart)
+ self.stream.on('secureConnect', onStart);
} else {
- self.socket.on('connect', onStart)
+ self.socket.on('connect', onStart);
}
function onStart() {
- self.connected = true
- self.emit('start')
+ self.connected = true;
+ self.emit('start');
}
self.stream.on('data', function onData(chunk) {
~messageLength
? fetchBody(chunk)
- : fetchHeader(chunk)
- })
+ : fetchHeader(chunk);
+ });
function fetchHeader(chunk) {
if (bufferJoiner.length + chunk.length >= 9) {
- var header = bufferJoiner.add(chunk).join()
- eventLength = header.readUInt32BE(0)
- messageLength = header.readUInt32BE(4)
- messagetype = header.readInt8(8)
- fetchBody(chunk.slice(9))
+ var header = bufferJoiner.add(chunk).join();
+ eventLength = header.readUInt32BE(0);
+ messageLength = header.readUInt32BE(4);
+ messagetype = header.readInt8(8);
+ fetchBody(chunk.slice(9));
} else {
- bufferJoiner.add(chunk)
+ bufferJoiner.add(chunk);
}
}
function fetchBody(chunk) {
- var raw, event, data
- var chunkLength = chunk.length
- var bytesLeft = (eventLength + messageLength) - bufferJoiner.length
+ var raw, event, data;
+ var chunkLength = chunk.length;
+ var bytesLeft = (eventLength + messageLength) - bufferJoiner.length;
if (chunkLength >= bytesLeft) {
- raw = bufferJoiner.add(chunk.slice(0, bytesLeft)).join()
- event = JSON.parse(raw.slice(0, eventLength))
- data = messagetype ? raw.slice(eventLength) : JSON.parse(raw.slice(eventLength).toString())
+ raw = bufferJoiner.add(chunk.slice(0, bytesLeft)).join();
+ event = JSON.parse(raw.slice(0, eventLength));
+ data = messagetype ? raw.slice(eventLength) : JSON.parse(raw.slice(eventLength).toString());
- eventLength = -1
- messageLength = -1
+ eventLength = -1;
+ messageLength = -1;
- self.emit(['data'].concat(event), data)
+ self.emit(['data'].concat(event), data);
if (chunkLength - bytesLeft) {
- fetchHeader(chunk.slice(bytesLeft))
+ fetchHeader(chunk.slice(bytesLeft));
}
- return
+ return;
}
- bufferJoiner.add(chunk)
+ bufferJoiner.add(chunk);
}
self.socket.on('close', function onClose(hadError) {
- self.socket.destroy()
- self.socket = undefined
- self.connected = false
+ self.socket.destroy();
+ self.socket = undefined;
+ self.connected = false;
if (hadError) {
- self.emit('close', hadError, arguments[1])
+ self.emit('close', hadError, arguments[1]);
} else {
- self.emit('close')
+ self.emit('close');
}
- self.retry && self.reconnect()
- })
+ self.retry && self.reconnect();
+ });
self.socket.on('error', function (err) {
- !self.retry && self.emit('error', err || new Error('An Unknown Error occured'))
- })
+ !self.retry && self.emit('error', err || new Error('An Unknown Error occured'));
+ });
self.socket.on('timeout', function onIdle() {
- self.emit('idle')
- self.timeout && self.socket.setTimeout(this.timeout)
- })
+ self.emit('idle');
+ self.timeout && self.socket.setTimeout(this.timeout);
+ });
}
View
64 test/buffer-tcp.test.js
@@ -1,57 +1,57 @@
var net = require('net'),
fs = require ('fs'),
expect = require('chai').expect,
- nssocket = require('../')
+ nssocket = require('../');
-var trollface = fs.readFileSync('test/fixtures/trollface.jpg')
-var TCP_PORT = 5467
+var trollface = fs.readFileSync('test/fixtures/trollface.jpg');
+var TCP_PORT = 5467;
describe('nssocket/tcp/buffer', function () {
before(function (done) {
- var self = this
+ var self = this;
this.server = net.createServer(function (inbound) {
- self.inbound = inbound
- done()
- })
+ self.inbound = inbound;
+ done();
+ });
this.server.listen(TCP_PORT, function () {
- self.outbound = nssocket({ delimiter: '/' }).connect(TCP_PORT)
- })
- })
+ self.outbound = nssocket({ delimiter: '/' }).connect(TCP_PORT);
+ });
+ });
after(function () {
- this.server.close()
- this.outbound.end()
- this.inbound.end()
- })
+ this.server.close();
+ this.outbound.end();
+ this.inbound.end();
+ });
describe('#send()', function () {
- it('should correctly receive multi messages chunks / json', testMulti(5, { foo: 'bar' }))
- it('should correctly receive multi messages chunks / buffer', testMulti(5, Buffer('foo:bar')))
- it('should correctly receive multi messages chunks / large buffer', testMulti(5, trollface))
- })
-})
+ it('should correctly receive multi messages chunks / json', testMulti(5, { foo: 'bar' }));
+ it('should correctly receive multi messages chunks / buffer', testMulti(5, Buffer('foo:bar')));
+ it('should correctly receive multi messages chunks / large buffer', testMulti(5, trollface));
+ });
+});
function testMulti(n, data) {
return function (done) {
- var self = this
- var message = this.outbound.createMessage('test/multi', data)
- var buffer = Buffer.concat(arrayOf(message, n), message.length * n)
+ var self = this;
+ var message = this.outbound.createMessage('test/multi', data);
+ var buffer = Buffer.concat(arrayOf(message, n), message.length * n);
function onMessage(data) {
- n --
- expect(data).to.be.eql(data)
+ n --;
+ expect(data).to.be.eql(data);
if (!n) {
- self.outbound.off('data/test/multi', onMessage)
- done()
+ self.outbound.off('data/test/multi', onMessage);
+ done();
}
}
- this.outbound.on('data/test/multi', onMessage)
- this.inbound.write(buffer)
- }
+ this.outbound.on('data/test/multi', onMessage);
+ this.inbound.write(buffer);
+ };
}
function arrayOf(what, howmany) {
- var arr = []
+ var arr = [];
for (var i = 0; i < howmany; i++) {
- arr.push(what)
+ arr.push(what);
}
- return arr
+ return arr;
}
View
64 test/buffer-tls.test.js
@@ -1,61 +1,61 @@
var tls = require('tls'),
fs = require ('fs'),
expect = require('chai').expect,
- nssocket = require('../')
+ nssocket = require('../');
-var trollface = fs.readFileSync('test/fixtures/trollface.jpg')
-var TCP_PORT = 5467
+var trollface = fs.readFileSync('test/fixtures/trollface.jpg');
+var TCP_PORT = 5467;
describe('nssocket/tls/buffer', function () {
before(function (done) {
- var self = this
+ var self = this;
this.server = tls.createServer({
key: fs.readFileSync('test/fixtures/ryans-key.pem'),
cert: fs.readFileSync('test/fixtures/ryans-cert.pem'),
ca: fs.readFileSync('test/fixtures/ryans-csr.pem')
}, function (inbound) {
- self.inbound = inbound
- done()
- })
+ self.inbound = inbound;
+ done();
+ });
this.server.listen(TCP_PORT, function () {
- self.outbound = nssocket({ type : 'tls', delimiter: '/' }).connect(TCP_PORT)
- })
- })
+ self.outbound = nssocket({ type : 'tls', delimiter: '/' }).connect(TCP_PORT);
+ });
+ });
after(function () {
- this.server.close()
- this.inbound.end()
- this.outbound.end()
- })
+ this.server.close();
+ this.inbound.end();
+ this.outbound.end();
+ });
describe('#send()', function () {
- it('should correctly receive multi messages chunks / json', testMulti(5, { foo: 'bar' }))
- it('should correctly receive multi messages chunks / buffer', testMulti(5, Buffer('foo:bar')))
- it('should correctly receive multi messages chunks / large buffer', testMulti(5, trollface))
- })
-})
+ it('should correctly receive multi messages chunks / json', testMulti(5, { foo: 'bar' }));
+ it('should correctly receive multi messages chunks / buffer', testMulti(5, Buffer('foo:bar')));
+ it('should correctly receive multi messages chunks / large buffer', testMulti(5, trollface));
+ });
+});
function testMulti(n, data) {
return function (done) {
- var self = this
- var message = this.outbound.createMessage('test/multi', data)
- var buffer = Buffer.concat(arrayOf(message, n), message.length * n)
+ var self = this;
+ var message = this.outbound.createMessage('test/multi', data);
+ var buffer = Buffer.concat(arrayOf(message, n), message.length * n);
function onMessage(data) {
- n --
- expect(data).to.be.eql(data)
+ n --;
+ expect(data).to.be.eql(data);
if (!n) {
- self.outbound.off('data/test/multi', onMessage)
- done()
+ self.outbound.off('data/test/multi', onMessage);
+ done();
}
}
- this.outbound.on('data/test/multi', onMessage)
- this.inbound.write(buffer)
- }
+ this.outbound.on('data/test/multi', onMessage);
+ this.inbound.write(buffer);
+ };
}
function arrayOf(what, howmany) {
- var arr = []
+ var arr = [];
for (var i = 0; i < howmany; i++) {
- arr.push(what)
+ arr.push(what);
}
- return arr
+ return arr;
}
View
58 test/create-server.test.js
@@ -10,48 +10,48 @@ var net = require('net'),
fs = require ('fs'),
path = require('path'),
assert = require('chai').assert,
- nssocket = require('../')
+ nssocket = require('../');
-var PORT = 9568
-var HOST = '127.0.0.1'
-var HOSTNAME = 'localhost'
-var PIPE = path.join(__dirname, 'fixtures', 'nssocket.sock')
+var PORT = 9568;
+var HOST = '127.0.0.1';
+var HOSTNAME = 'localhost';
+var PIPE = path.join(__dirname, 'fixtures', 'nssocket.sock');
describe('nssocket/create-server', function () {
describe('#listen()', function () {
before(function() {
- try { fs.unlinkSync(FD) }
+ try { fs.unlinkSync(FD); }
catch (err) {}
- })
+ });
afterEach(function (done) {
- this.server.close(done)
- this.outbound.end()
- this.inbound.end()
- })
- it('should create a full-duplex namespaced socket / (PORT)', testWith(PORT))
- it('should create a full-duplex namespaced socket / (PORT, HOST)', testWith(PORT, HOST))
- it('should create a full-duplex namespaced socket / (PORT, HOSTNAME)', testWith(PORT, HOSTNAME))
- it('should create a full-duplex namespaced socket / (PIPE)', testWith(PIPE))
- })
-})
+ this.server.close(done);
+ this.outbound.end();
+ this.inbound.end();
+ });
+ it('should create a full-duplex namespaced socket / (PORT)', testWith(PORT));
+ it('should create a full-duplex namespaced socket / (PORT, HOST)', testWith(PORT, HOST));
+ it('should create a full-duplex namespaced socket / (PORT, HOSTNAME)', testWith(PORT, HOSTNAME));
+ it('should create a full-duplex namespaced socket / (PIPE)', testWith(PIPE));
+ });
+});
function testWith() {
- var args = [].slice.call(arguments)
+ var args = [].slice.call(arguments);
return function (done) {
- var self = this
+ var self = this;
self.server = nssocket.createServer(function (inbound) {
- self.inbound = inbound
+ self.inbound = inbound;
self.outbound.on(['data', 'here', 'is'], function (data) {
- assert.deepEqual(this.event, ['data', 'here', 'is'])
- assert.equal(data, 'something.')
- done()
- })
+ assert.deepEqual(this.event, ['data', 'here', 'is']);
+ assert.equal(data, 'something.');
+ done();
+ });
self.inbound.send(['here', 'is'], 'something.');
- })
+ });
self.server.listen.apply(self.server, args.concat(function () {
- self.outbound = nssocket()
- self.outbound.connect.apply(self.outbound, args)
- }))
- }
+ self.outbound = nssocket();
+ self.outbound.connect.apply(self.outbound, args);
+ }));
+ };
}
View
56 test/tcp-reconnect.test.js
@@ -10,48 +10,48 @@ var net = require('net'),
fs = require ('fs'),
path = require('path'),
assert = require('chai').assert,
- nssocket = require('../')
+ nssocket = require('../');
-var TCP_PORT = 30105
+var TCP_PORT = 30105;
var TCP_OPTIONS = {
type : 'tcp4',
delimiter: '.}',
reconnect: true,
retryInterval: 200
-}
+};
describe('nssocket/tcp/reconnect', function () {
after(function (done) {
- this.server.close(done)
- this.outbound.end()
- this.inbound.end()
- })
+ this.server.close(done);
+ this.outbound.end();
+ this.inbound.end();
+ });
describe('client', function () {
it('should connect', function (done) {
- var self = this
- self.outbound = nssocket(TCP_OPTIONS).connect(TCP_PORT)
- self.server = nssocket.createServer(TCP_OPTIONS, done.bind(null, null))
+ var self = this;
+ self.outbound = nssocket(TCP_OPTIONS).connect(TCP_PORT);
+ self.server = nssocket.createServer(TCP_OPTIONS, done.bind(null, null));
setTimeout(function () {
- self.server.listen(TCP_PORT)
- }, 200)
- })
+ self.server.listen(TCP_PORT);
+ }, 200);
+ });
it('should handle reconnection', function (done) {
- var self = this
+ var self = this;
self.server.close(function () {
self.server = nssocket.createServer(TCP_OPTIONS, function (inbound) {
- self.inbound = inbound
- done()
- }).listen(TCP_PORT)
- })
- self.outbound.end()
- })
+ self.inbound = inbound;
+ done();
+ }).listen(TCP_PORT);
+ });
+ self.outbound.end();
+ });
it('should be able to send after reconnection', function (done) {
this.outbound.once('data.}here.}is', function (data) {
- assert.deepEqual(this.event, ['data', 'here', 'is'])
- assert.equal(data, 'something.')
- done()
- })
- this.inbound.send('here.}is', 'something.')
- })
- })
-})
+ assert.equal(data, 'something.');
+ done();
+ });
+ this.inbound.send('here.}is', 'something.');
+ });
+ });
+});
View
142 test/tcp.test.js
@@ -10,108 +10,108 @@ var net = require('net'),
fs = require ('fs'),
path = require('path'),
assert = require('chai').assert,
- nssocket = require('../')
+ nssocket = require('../');
-var TCP_PORT = 30105
+var TCP_PORT = 30105;
var TCP_OPTIONS = {
type : 'tcp4',
delimiter: '.}',
reconnect: true,
retryInterval: 200
-}
+};
describe('nssocket/tcp', function () {
after(function (done) {
- this.server.close(done)
- })
+ this.server.close(done);
+ });
describe('#()', function () {
before(function () {
- this.outbound = nssocket(TCP_OPTIONS)
- })
+ this.outbound = nssocket(TCP_OPTIONS);
+ });
it('should create a wrapped socket', function () {
- assert.instanceOf(this.outbound, nssocket)
- })
+ assert.instanceOf(this.outbound, nssocket);
+ });
it('should have the proper configuration settings', function () {
- assert.equal(this.outbound.type, TCP_OPTIONS.type)
- assert.equal(this.outbound.delimiter, TCP_OPTIONS.delimiter)
- })
- })
+ assert.equal(this.outbound.type, TCP_OPTIONS.type);
+ assert.equal(this.outbound.delimiter, TCP_OPTIONS.delimiter);
+ });
+ });
describe('#connect()', function () {
it('should actually connect', function (done) {
- var self = this
+ var self = this;
self.server = nssocket.createServer(TCP_OPTIONS, function (inbound) {
- self.inbound = inbound
- done()
+ self.inbound = inbound;
+ done();
}).listen(TCP_PORT, function () {
- self.outbound.connect(TCP_PORT)
- })
- })
- })
+ self.outbound.connect(TCP_PORT);
+ });
+ });
+ });
describe('#setIdle()', function () {
it('should save idle timeout', function (done) {
- this.outbound.once('idle', done)
- this.outbound.setIdle(100)
- })
- })
+ this.outbound.once('idle', done);
+ this.outbound.setIdle(100);
+ });
+ });
describe('#createMessage()', function () {
it('should package json into binary messages', function () {
- var rawMessage = this.outbound.createMessage(['foo', 'bar'], { content: 'foobar!' })
- var eventLength = rawMessage.readUInt32BE(0)
- var messageLength = rawMessage.readUInt32BE(4)
- var messagetype = rawMessage.readInt8(8)
- var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
- var data = JSON.parse(rawMessage.slice(9 + eventLength).toString())
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], { content: 'foobar!' });
+ var eventLength = rawMessage.readUInt32BE(0);
+ var messageLength = rawMessage.readUInt32BE(4);
+ var messagetype = rawMessage.readInt8(8);
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9));
+ var data = JSON.parse(rawMessage.slice(9 + eventLength).toString());
- assert.equal(messagetype, 0)
- assert.deepEqual(event, ['foo', 'bar'])
- assert.deepEqual(data, { content: 'foobar!' })
- })
+ assert.equal(messagetype, 0);
+ assert.deepEqual(event, ['foo', 'bar']);
+ assert.deepEqual(data, { content: 'foobar!' });
+ });
it('should package buffers into binary messages', function () {
- var rawMessage = this.outbound.createMessage(['foo', 'bar'], Buffer('foo::bar'))
- var eventLength = rawMessage.readUInt32BE(0)
- var messageLength = rawMessage.readUInt32BE(4)
- var messagetype = rawMessage.readInt8(8)
- var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
- var data = rawMessage.slice(9 + eventLength).toString()
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], Buffer('foo::bar'));
+ var eventLength = rawMessage.readUInt32BE(0);
+ var messageLength = rawMessage.readUInt32BE(4);
+ var messagetype = rawMessage.readInt8(8);
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9));
+ var data = rawMessage.slice(9 + eventLength).toString();
- assert.equal(messagetype, 1)
- assert.deepEqual(event, ['foo', 'bar'])
- assert.equal(data.toString(), 'foo::bar')
- })
- })
+ assert.equal(messagetype, 1);
+ assert.deepEqual(event, ['foo', 'bar']);
+ assert.equal(data.toString(), 'foo::bar');
+ });
+ });
describe('#on()', function () {
it('should handle namespaced events', function (done) {
- var rawMessage = this.outbound.createMessage(['here', 'is'], 'something.')
+ var rawMessage = this.outbound.createMessage(['here', 'is'], 'something.');
this.inbound.once('data.}here.}is', function (data) {
- assert.deepEqual(this.event, ['data', 'here', 'is'])
- assert.equal(data, 'something.')
- done()
- })
- this.outbound.write(rawMessage)
- })
- })
+ assert.deepEqual(this.event, ['data', 'here', 'is']);
+ assert.equal(data, 'something.');
+ done();
+ });
+ this.outbound.write(rawMessage);
+ });
+ });
describe('#send()', function () {
it('should package and send json messages', function (done) {
this.inbound.once('data.}hello.}world', function (data) {
- assert.deepEqual(this.event, ['data', 'hello', 'world'])
- assert.deepEqual(data, { content: 'foobar!' })
- done()
- })
- this.outbound.send(['hello','world'], { content: 'foobar!' })
- })
+ assert.deepEqual(this.event, ['data', 'hello', 'world']);
+ assert.deepEqual(data, { content: 'foobar!' });
+ done();
+ });
+ this.outbound.send(['hello','world'], { content: 'foobar!' });
+ });
it('should package and send binary messages', function (done) {
this.inbound.once('data.}hello.}world', function (data) {
- assert.deepEqual(this.event, ['data', 'hello', 'world'])
- assert.equal(data.toString(), 'foo::bar')
- done()
- })
- this.outbound.send(['hello','world'], Buffer('foo::bar'))
- })
- })
+ assert.deepEqual(this.event, ['data', 'hello', 'world']);
+ assert.equal(data.toString(), 'foo::bar');
+ done();
+ });
+ this.outbound.send(['hello','world'], Buffer('foo::bar'));
+ });
+ });
describe('#end()', function () {
it('should close the connection', function (done) {
- this.outbound.on('close', done)
- this.inbound.end()
- })
- })
-})
+ this.inbound.end();
+ });
+ });
+});
View
138 test/tls.test.js
@@ -10,106 +10,106 @@ var net = require('net'),
fs = require ('fs'),
path = require('path'),
assert = require('chai').assert,
- nssocket = require('../')
+ nssocket = require('../');
-var TLS_PORT = 30105
+var TLS_PORT = 30105;
var TLS_OPTIONS = {
type: 'tls',
delimiter: '.}',
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'ryans-key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'ryans-cert.pem')),
ca: fs.readFileSync(path.join(__dirname, 'fixtures', 'ryans-csr.pem'))
-}
+};
describe('nssocket/tls', function () {
describe('#()', function () {
before(function () {
- this.outbound = nssocket({ type: 'tls', delimiter: '.}' })
- })
+ this.outbound = nssocket({ type: 'tls', delimiter: '.}' });
+ });
it('should create a wrapped socket', function () {
- assert.instanceOf(this.outbound, nssocket)
- })
+ assert.instanceOf(this.outbound, nssocket);
+ });
it('should have the proper configuration settings', function () {
- assert.equal(this.outbound.type, TLS_OPTIONS.type)
- assert.equal(this.outbound.delimiter, TLS_OPTIONS.delimiter)
- })
- })
+ assert.equal(this.outbound.type, TLS_OPTIONS.type);
+ assert.equal(this.outbound.delimiter, TLS_OPTIONS.delimiter);
+ });
+ });
describe('#connect()', function () {
it('should actually connect', function (done) {
- var self = this
+ var self = this;
self.server = nssocket.createServer(TLS_OPTIONS, function (inbound) {
- self.inbound = inbound
- done()
+ self.inbound = inbound;
+ done();
}).listen(TLS_PORT, function () {
- self.outbound.connect(TLS_PORT)
- })
- })
- })
+ self.outbound.connect(TLS_PORT);
+ });
+ });
+ });
describe('#setIdle()', function () {
it('should save idle timeout', function (done) {
- this.outbound.once('idle', done)
- this.outbound.setIdle(100)
- })
- })
+ this.outbound.once('idle', done);
+ this.outbound.setIdle(100);
+ });
+ });
describe('#createMessage()', function () {
it('should package json into binary messages', function () {
- var rawMessage = this.outbound.createMessage(['foo', 'bar'], { content: 'foobar!' })
- var eventLength = rawMessage.readUInt32BE(0)
- var messageLength = rawMessage.readUInt32BE(4)
- var messagetype = rawMessage.readInt8(8)
- var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
- var data = JSON.parse(rawMessage.slice(9 + eventLength).toString())
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], { content: 'foobar!' });
+ var eventLength = rawMessage.readUInt32BE(0);
+ var messageLength = rawMessage.readUInt32BE(4);
+ var messagetype = rawMessage.readInt8(8);
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9));
+ var data = JSON.parse(rawMessage.slice(9 + eventLength).toString());
- assert.equal(messagetype, 0)
- assert.deepEqual(event, ['foo', 'bar'])
- assert.deepEqual(data, { content: 'foobar!' })
- })
+ assert.equal(messagetype, 0);
+ assert.deepEqual(event, ['foo', 'bar']);
+ assert.deepEqual(data, { content: 'foobar!' });
+ });
it('should package buffers into binary messages', function () {
- var rawMessage = this.outbound.createMessage(['foo', 'bar'], Buffer('foo::bar'))
- var eventLength = rawMessage.readUInt32BE(0)
- var messageLength = rawMessage.readUInt32BE(4)
- var messagetype = rawMessage.readInt8(8)
- var event = JSON.parse(rawMessage.slice(9, eventLength + 9))
- var data = rawMessage.slice(9 + eventLength).toString()
+ var rawMessage = this.outbound.createMessage(['foo', 'bar'], Buffer('foo::bar'));
+ var eventLength = rawMessage.readUInt32BE(0);
+ var messageLength = rawMessage.readUInt32BE(4);
+ var messagetype = rawMessage.readInt8(8);
+ var event = JSON.parse(rawMessage.slice(9, eventLength + 9));
+ var data = rawMessage.slice(9 + eventLength).toString();
- assert.equal(messagetype, 1)
- assert.deepEqual(event, ['foo', 'bar'])
- assert.equal(data.toString(), 'foo::bar')
- })
- })
+ assert.equal(messagetype, 1);
+ assert.deepEqual(event, ['foo', 'bar']);
+ assert.equal(data.toString(), 'foo::bar');
+ });
+ });
describe('#on()', function () {
it('should handle namespaced events', function (done) {
- var rawMessage = this.outbound.createMessage(['here', 'is'], 'something.')
+ var rawMessage = this.outbound.createMessage(['here', 'is'], 'something.');
this.inbound.once('data.}here.}is', function (data) {
- assert.deepEqual(this.event, ['data', 'here', 'is'])
- assert.equal(data, 'something.')
- done()
- })
- this.outbound.write(rawMessage)
- })
- })
+ assert.deepEqual(this.event, ['data', 'here', 'is']);
+ assert.equal(data, 'something.');
+ done();
+ });
+ this.outbound.write(rawMessage);
+ });
+ });
describe('#send()', function () {
it('should package and send json messages', function (done) {
this.inbound.once('data.}hello.}world', function (data) {
- assert.deepEqual(this.event, ['data', 'hello', 'world'])
- assert.deepEqual(data, { content: 'foobar!' })
- done()
- })
- this.outbound.send(['hello','world'], { content: 'foobar!' })
- })
+ assert.deepEqual(this.event, ['data', 'hello', 'world']);
+ assert.deepEqual(data, { content: 'foobar!' });
+ done();
+ });
+ this.outbound.send(['hello','world'], { content: 'foobar!' });
+ });
it('should package and send binary messages', function (done) {
this.inbound.once('data.}hello.}world', function (data) {
- assert.deepEqual(this.event, ['data', 'hello', 'world'])
- assert.equal(data.toString(), 'foo::bar')
- done()
- })
- this.outbound.send(['hello','world'], Buffer('foo::bar'))
- })
- })
+ assert.deepEqual(this.event, ['data', 'hello', 'world']);
+ assert.equal(data.toString(), 'foo::bar');
+ done();
+ });
+ this.outbound.send(['hello','world'], Buffer('foo::bar'));
+ });
+ });
describe('#end()', function () {
it('should close the connection', function (done) {
- this.outbound.on('close', done)
- this.inbound.end()
- })
- })
-})
+ this.inbound.end();
+ });
+ });
+});
Please sign in to comment.
Something went wrong with that request. Please try again.