Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

[test api doc dist] Finalized first pass at NsSocket@0.3.0

  • Loading branch information...
commit 01947248ea98fea11ba88dd70ef61e894ed7b2dd 1 parent 3db48ee
@indexzero indexzero authored
View
235 README.md
@@ -1,139 +1,112 @@
-# NsSocket
- NameSpace based Event based Buffered TCP/TLS Stream
+# nssocket
+An elegant way to define lightweight protocols on-top of TCP/TLS sockets in node.js
-## Purpose
- Wrap a network socket to change (text-based) network communication into events
+## Installation
-## Major Dependency
-NsSocket Inherits from [eventemitter2](http://github.com/hij1nx/EventEmitter2.git)
+### Installing npm (node package manager)
+```
+ curl http://npmjs.org/install.sh | sh
+```
-## Installation
-<pre>
-npm install nssocket
-or
-git clone git@github.com:nodejitsu/nssocket.git
-</pre>
-
-## API
-
-### new nssocket.NsSocket(socket, config)
- - `socket` network (tcp or tls) socket
- - `config` config options for this NsSocket
- <pre>
- // default values of config, if not specified
- config = {
- type : 'tcp',
- delimiter : '::',
- connected : false,
- msgLength : 3,
- maxListeners : 10,
- }
- </pre>
-
-### NsSocket.send(nameArray, data)
- - `nameArray` Array describing the namespace, e.g. `['some', 'namespace']`
- - `data` string data, (use of `JSON.stringify` and `JSON.parse` is highly recommended)
- *Do Not Use your delimiter in your nameArray or data*
-
-### NsSocket.on(event, callback)
- - `event` name of the event
- - `callback` - the callback function
- Register callbacks to events on this NsSocket
-
-### NsSocket.emit(event, [data], ...)
- - `event` event to emit
- *use at your own risk*
- It is recommended that you do not emit events on the nssocket itself.
-
-### NsSocket.connect(port, [host], [callback])
- - `port` destination port
- - `host` destination host, ip or hostname
- - `callback` callback on successful `connect`
-This is a very thin wrapper around `net` or `tls`
-
-### NsSocket.end()
- - closes the current socket, emits `close` event, possibly also `error`
-
-### NsSocket.destroy()
- - remove all listeners, destroys socket, clears buffer
- - should normally use `NsSocket.end()`
-
-### Events
-
-#### start
-`function () {}`
-
-Emitted once the underlying socket has connected/started
-#### data
-`function (data) {}`
-Emitted on raw data received on the underlying socket
-
-#### data::some::names ...
-`function (nameArray, data) {}`
-Emitted once when a full message has been received on the socket, the output
- corresponds to the input given to `NsSocket.send`
-
-e.g.
-<pre>
-nsSocket.on('data::some::evented', function (tags, data) {
- console.log('Got a message in space: ', tags);
- console.log('With the data of: ', data);
-}
-</pre>
-
-#### error
-`function (err) {}`
-
-Emitted when there are any errors
-#### close
-`function (hadErr) {}`
-
-Emitted when the underlying connection is closed, `hadErr` will be true if
-there were any errors.
-#### idle
-emitted when the socket has been idle,
-only emitted if `setKeepAlive` or `setTimeout` has been bound
-
-## Usage Demo
-```javascript
-var net = require('net'),
- nssocket = require('nssocket');
-
-// Config object
-var config = {
- delimiter : '::' // default (recommended)
- type : 'tcp' // default (tcp, tls)
- msgLength : 3 // default (can be any length, technically even 1)
-};
-
-// socket gets wrapped
-var socket = new net.Socket({ type: 'tcp4'}),
- nsSocket = nssocket.NsSocket(socket, config);
-
-nsSocket.connect(80, '127.0.0.1', function onConnect() {
- // pass in an array
- nsSocket.send(
- ['hello', 'world'],
- JSON.stringify({ foo:1, bar:2 })
- );
- console.dir('sent!');
-});
+### Installing nssocket
+```
+ [sudo] npm install nssocket
```
-## Coming soon
-- More & Better Tests
-- Make Demo in examples/
-- Add automatic socket creation (no more passing in sockets!)
-- Add UDP support
-- Add nssocket.Server functionality (returns a nssocket!)
-- Cake(?)
+## 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.
+
+With `nssocket` this tedious bookkeeping work is done automatically for you in two ways:
-## Demo
- TBA
+1. Leverages wildcard and namespaced events from [EventEmitter2][0]
+2. Automatically serializes messages passed to `.send()` and deserializes messages from `data` events.
+3. Automatically wraps TCP connections with TLS using [a known workaround][1]
+
+## Messages
+Messages in `nssocket` are serialized JSON arrays of the following form:
+
+``` js
+ ["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.
+
+## Usage
+So get on with it right? _SHOW ME SOME CODE!_
+
+### Simple Example
+``` js
+ var nssocket = require('nssocket');
+
+ //
+ // Create an `nssocket` TCP server
+ //
+ var server = nssocket.createServer(function (socket) {
+ //
+ // Here `socket` will be an instance of `nssocket.NsSocket`.
+ //
+ socket.send(['you', 'there']);
+ 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);
+
+ var outbound = new nssocket.NsSocket();
+ outbound.data(['you', 'there'], function () {
+ outbound.send(['iam', 'here'], { iam: true, indeedHere: true });
+ });
+
+ outbound.connect(6785);
+```
-### Maintainers
-[Paolo Fragmenti](https://github.com/hij1nx),
-[Jameson Lee](https://github.com/drjackal)
+### Methods
+
+#### 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:
+
+``` js
+ //
+ // These two statements are equivalent
+ //
+ someSocket.on(['data', 'some', 'event'], function (data) { });
+ someSocket.data(['some', 'event'], function (data) { });
+```
+
+#### 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][2] and should be run through [npm][3]:
+
+``` bash
+ $ npm test
+```
-### License
-MIT?
+#### Author: [Nodejitsu](http://www.nodejitsu.com)
+#### Contributors: [Paolo Fragomeni](http://github.com/hij1nx), [Charlie Robbins](http://github.com/indexzero), [Jameson Lee](http://github.com/drjackal)
+
+[0]: http://github.com/hij1nx/eventemitter2
+[1]: https://gist.github.com/848444
+[2]: http://vowsjs.org
+[3]: http://npmjs.org
View
33 examples/simple-protocol.js
@@ -0,0 +1,33 @@
+var nssocket = require('../lib/nssocket');
+
+//
+// Create an `nssocket` TCP server
+//
+var server = nssocket.createServer(function (socket) {
+ //
+ // Here `socket` will be an instance of `nssocket.NsSocket`.
+ //
+ socket.send(['you', 'there']);
+ 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);
+
+var outbound = new nssocket.NsSocket();
+outbound.data(['you', 'there'], function () {
+ outbound.send(['iam', 'here'], { iam: true, indeedHere: true });
+});
+
+outbound.connect(6785);
View
107 lib/common.js
@@ -0,0 +1,107 @@
+/*
+ * common.js
+ *
+ * (C) 2011, Nodejitsu Inc.
+ */
+
+var fs = require('fs'),
+ tls = require('tls'),
+ net = require('net'),
+ crypto = require('crypto');
+
+exports.createSocket = function (options) {
+ options = options || {};
+ options.type = options.type || 'tcp4';
+
+ return options.type === 'tls'
+ ? exports.createTlsSocket(options)
+ : new net.Socket(options);
+};
+
+//
+// ### function createTlsSocket (options)
+// #### @options {Object} Tls options like in tls.js
+// #### Should behave like tls.connect, except it just creates the socket like net.Socket
+// #### Also has a function called 'connect' that will allow` it to connect to a remote host
+// this is a rip of tls.js's connect
+//
+exports.createTlsSocket = function(options) {
+ var self = this;
+
+ function setupTlsPipe () {
+ var sslcontext = crypto.createCredentials(options),
+ pair = tls.createSecurePair(sslcontext, false),
+ cleartext = pipe(pair, socket);
+
+ pair.on('secure', function() {
+ var verifyError = pair.ssl.verifyError();
+
+ if (verifyError) {
+ cleartext.authorized = false;
+ cleartext.authorizationError = verifyError;
+ }
+ else {
+ cleartext.authorized = true;
+ }
+ });
+
+ //
+ // Setup the cleartext stream to have a `.connect()` method
+ // which passes through to the underlying TCP socket.
+ //
+ socket.cleartext = cleartext;
+ cleartext._controlReleased = true;
+ }
+
+ //
+ // Setup the TLS connection over the existing TCP connection:
+ //
+ // 1. Create a new instance of `net.Socket`.
+ // 2. Create a new set of credentials with `options`.
+ // 3. Create the TLS pair
+ // 4. Pipe the TLS pair to the TCP socket
+ //
+ var socket = new net.Stream({ type: 'tcp4' });
+
+ socket.on('connect', function () {
+ setupTlsPipe(socket);
+ });
+
+ return socket;
+};
+
+//
+// helper function for createTlsSocket
+//
+function pipe(pair, socket) {
+ pair.encrypted.pipe(socket);
+ socket.pipe(pair.encrypted);
+
+ pair.fd = socket.fd;
+ var cleartext = pair.cleartext;
+ cleartext.socket = socket;
+ cleartext.encrypted = pair.encrypted;
+ cleartext.authorized = false;
+
+ function onerror(e) {
+ if (cleartext._controlReleased) {
+ cleartext.emit('error', e);
+ }
+ }
+
+ function onclose() {
+ socket.removeListener('error', onerror);
+ socket.removeListener('close', onclose);
+ socket.removeListener('timeout', ontimeout);
+ }
+
+ function ontimeout() {
+ cleartext.emit('timeout');
+ }
+
+ socket.on('error', onerror);
+ socket.on('close', onclose);
+ socket.on('timeout', ontimeout);
+
+ return cleartext;
+}
View
88 lib/nssocket.js
@@ -1,11 +1,15 @@
/*
- * nssocker.js - Wraps a TLS/TCP socket to emit namespace events also auto-buffers.
- * nssocket
+ * nssocket.js - Wraps a TLS/TCP socket to emit namespace events also auto-buffers.
+ *
* (C) 2011, Nodejitsu Inc.
+ *
*/
-var util = require('util'),
- events2 = require('eventemitter2');
+var net = require('net'),
+ tls = require('tls'),
+ util = require('util'),
+ events2 = require('eventemitter2'),
+ common = require('./common');
//
// ### function NsSocket (socket, options)
@@ -19,12 +23,15 @@ var NsSocket = exports.NsSocket = function (socket, options) {
return new NsSocket(socket, options);
}
- // There has to be a socket to wrap
- if (!socket) {
- this.emit('error', new Error('Cannot wrap undefined socket.'));
- return null;
+ //
+ // If there is no Socket instnace to wrap,
+ // create one.
+ //
+ if (!options) {
+ options = socket;
+ socket = common.createSocket(options);
}
-
+
//
// Options should be
//
@@ -34,9 +41,8 @@ var NsSocket = exports.NsSocket = function (socket, options) {
// msgLength : 3 //number of segments in a complete message
// }
//
- options = options || {};
+ options = options || {};
- // some default options
var self = this,
startName;
@@ -46,7 +52,7 @@ var NsSocket = exports.NsSocket = function (socket, options) {
//
// Setup default instance variables.
//
- this._type = options.type || 'tcp',
+ this._type = options.type || 'tcp4',
this._delimiter = options.delimiter || '::';
this._buffer = '';
@@ -61,8 +67,10 @@ var NsSocket = exports.NsSocket = function (socket, options) {
// to separate some bindings. The main difference is on
// connection, some socket activities.
//
- if (this._type === 'tcp') {
+ if (this._type === 'tcp4') {
startName = 'connect';
+ socket.on('data', this._onData.bind(this));
+
// create a stub for the setKeepAlive functionality
self.setKeepAlive = function () {
socket.setKeepAlive.apply(socket, arguments);
@@ -70,10 +78,14 @@ var NsSocket = exports.NsSocket = function (socket, options) {
}
else if (this._type === 'tls') {
startName = 'secureConnection';
+ socket.once('connect', function () {
+ socket.cleartext.on('data', self._onData.bind(self));
+ });
+
// create a stub for the setKeepAlive functionality
self.setKeepAlive = function () {
socket.socket.setKeepAlive.apply(socket.socket, arguments);
- }
+ };
}
else {
// bad arguments, so throw an error
@@ -83,7 +95,6 @@ var NsSocket = exports.NsSocket = function (socket, options) {
// make sure we listen to the underlying socket
socket.on(startName, this._onStart.bind(this));
- socket.on('data', this._onData.bind(this));
socket.on('close', this._onClose.bind(this));
if (socket.socket) {
@@ -104,6 +115,29 @@ var NsSocket = exports.NsSocket = function (socket, options) {
util.inherits(NsSocket, events2.EventEmitter2);
//
+// ### function createServer (options, connectionListener)
+// #### @options {Object} **Optional**
+//
+//
+exports.createServer = function createServer(options, connectionListener) {
+ if (!connectionListener && typeof options === 'function') {
+ connectionListener = options;
+ options = {};
+ }
+
+ options.type = options.type || 'tcp4';
+ options.delimiter = options.delimiter || '::';
+
+ function onConnection (socket) {
+ connectionListener(new NsSocket(socket, options));
+ }
+
+ return options.type === 'tls'
+ ? tls.createServer(options, onConnection)
+ : net.createServer(options, onConnection);
+};
+
+//
// ### function send (data, callback)
// #### @event {Array|string} The array (or string) that holds the event name
// #### @data {Literal|Object} The data to be sent with the event.
@@ -131,8 +165,21 @@ NsSocket.prototype.send = function send(event, data, callback) {
return this.emit('error', new Error('NsSocket: sending on a bad socket'));
}
- // now actually write to the socket
- this.socket.write(Buffer(JSON.stringify(event.concat(data))), callback);
+ if (this.socket.cleartext) {
+ this.socket.cleartext.write(Buffer(JSON.stringify(event.concat(data))), callback);
+ }
+ else {
+ // now actually write to the socket
+ this.socket.write(Buffer(JSON.stringify(event.concat(data))), callback);
+ }
+};
+
+NsSocket.prototype.data = function (event, callback) {
+ if (typeof event === 'string') {
+ event = event.split(this._delimiter);
+ }
+
+ this.on(['data'].concat(event), callback);
};
//
@@ -145,7 +192,6 @@ NsSocket.prototype.setIdle = function setIdle(time) {
this._timeout = time;
};
-
//
// ### function destroy (void)
// #### forcibly destroys this nsSocket, unregister socket, remove all callbacks
@@ -163,9 +209,7 @@ NsSocket.prototype.destroy = function destroy() {
// do nothing on errors
}
}
- // this may lead to memory leaks?
- // delete this.socket;
-
+
// clear buffer
this.data = '';
this.emit('destroy');
@@ -227,7 +271,7 @@ NsSocket.prototype.connect = function connect(/*port, host, callback*/) {
host = host || '127.0.0.1';
this._connectOpts = [port, host, callback];
- if (['tcp', 'tls'].indexOf(this._type) === -1) {
+ if (['tcp4', 'tls'].indexOf(this._type) === -1) {
return this.emit('error', new Error('Unknown Socket Type'));
}
View
4 package.json
@@ -1,6 +1,6 @@
{
"name": "nssocket",
- "description": "Namespaced sockets with automatic buffering.",
+ "description": "An elegant way to define lightweight protocols on-top of TCP/TLS sockets in node.js",
"version": "0.2.5-1",
"author": "Nodejitsu Inc <info@nodejitsu.com>",
"maintainers": [
@@ -23,7 +23,7 @@
"node": "0.4.x"
},
"scripts": {
- "test": "vows --spec test/tcp-test.js"
+ "test": "vows test/*-test.js --spec"
}
}
View
48 test/create-server-test.js
@@ -0,0 +1,48 @@
+/*
+ * create-server-test.js : namespace socket unit test for TLS.
+ *
+ * (C) 2011, Nodejitsu Inc.
+ *
+ */
+
+var assert = require('assert'),
+ fs = require('fs'),
+ net = require('net'),
+ path = require('path'),
+ tls = require('tls'),
+ vows = require('vows'),
+ nssocket = require('../lib/nssocket');
+
+var PORT = 9564;
+
+vows.describe('nssocket/create-server').addBatch({
+ "When using NsSocket": {
+ "the createServer() method": {
+ topic: function () {
+ var outbound = new nssocket.NsSocket(),
+ server = nssocket.createServer(this.callback.bind(null, null, outbound));
+
+ server.listen(PORT);
+ outbound.connect(PORT);
+ },
+ "should create a full-duplex namespaced socket": {
+ topic: function (outbound, inbound) {
+ outbound.on(['data', 'here', 'is'], this.callback.bind(outbound, null));
+ inbound.send(['here', 'is'], 'something.');
+ },
+ "should handle namespaced events": function (_, data) {
+ assert.isArray(this.event);
+ assert.length(this.event, 3);
+ assert.isString(this.event[0]);
+ assert.isString(this.event[1]);
+ assert.isString(this.event[2]);
+ assert.isString(data);
+ assert.equal(this.event[0], 'data');
+ assert.equal(this.event[1], 'here');
+ assert.equal(this.event[2], 'is');
+ assert.equal(data, 'something.');
+ },
+ }
+ }
+ }
+}).export(module);
View
16 test/fixtures/ryans-cert.pem
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIICfzCCAegCCQCE5Xuxkur1mjANBgkqhkiG9w0BAQUFADCBgzELMAkGA1UEBhMC
+VVMxCzAJBgNVBAgMAk5ZMQswCQYDVQQHDAJOWTEVMBMGA1UECgwMSW50ZXJuZXQu
+Y29tMRgwFgYDVQQLDA9JbnRlcm5ldCBOaW5qYXMxDjAMBgNVBAMMBU51am9vMRkw
+FwYJKoZIhvcNAQkBFgpudU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g1eXUdLc/0FkJgvHuU/Wf/lLZ3+IL5L27VI2JMBFEhT
+fUhqSsfaNj8t593sIXcCQQDtWaKRz2QPAjhtM29xVihOBVPppdXdm1jSk25EciJX
+x4lrUXyNTeyQif0Hezp4WaYhVOS8uRGYnKH9eJzXQ5Pv
+-----END RSA PRIVATE KEY-----
View
71 test/tcp-test.js
@@ -1,27 +1,24 @@
/*
* nssocket-test.js : namespace socket unit test for TCP
*
- * (C) 2011, Nodejitsu Inc.
+ * (C) 2011, Nodejitsu Inc.
*
*/
-var fs = require('fs'),
+var assert = require('assert'),
+ fs = require('fs'),
+ net = require('net'),
path = require('path'),
- assert = require('assert'),
- spawn = require('child_process').spawn,
vows = require('vows'),
- net = require('net'),
NsSocket = require('../lib/nssocket').NsSocket;
var TCP_PORT = 30103;
-var tcpSocket = new net.Socket({ type:'tcp4' }),
- tcpServer = net.createServer(),
+var tcpServer = net.createServer(),
tcpOpt;
tcpOpt = {
- type : 'tcp',
- msgLength : 3,
+ type : 'tcp4',
delimiter: '.}'
};
@@ -29,30 +26,30 @@ tcpServer.listen(TCP_PORT);
vows.describe('nssocket').addBatch({
"When using NsSocket with TCP": {
- topic: new NsSocket(tcpSocket, tcpOpt),
- "should create a wrapped socket": function (instance) {
- assert.instanceOf(instance, NsSocket);
+ topic: new NsSocket(tcpOpt),
+ "should create a wrapped socket": function (outbound) {
+ assert.instanceOf(outbound, NsSocket);
},
- "should have the proper configuration settings": function (instance) {
- assert.equal(instance._type, tcpOpt.type);
- assert.equal(instance._delimiter, tcpOpt.delimiter);
+ "should have the proper configuration settings": function (outbound) {
+ assert.equal(outbound._type, tcpOpt.type);
+ assert.equal(outbound._delimiter, tcpOpt.delimiter);
},
"the connect() method": {
- topic: function (instance) {
+ topic: function (outbound) {
var that = this;
- tcpServer.on('connection', this.callback.bind(null, null, instance));
- instance.connect(TCP_PORT);
+ tcpServer.on('connection', this.callback.bind(null, null, outbound));
+ outbound.connect(TCP_PORT);
},
- "should actually connect": function (_, instance, wrapped) {
- assert.instanceOf(instance, NsSocket);
- assert.instanceOf(wrapped, net.Socket);
+ "should actually connect": function (_, outbound, inbound) {
+ assert.instanceOf(outbound, NsSocket);
+ assert.instanceOf(inbound, net.Socket);
},
- "the write() method": {
- topic: function (instance, wrapped) {
- instance.on('data.}here.}is', this.callback.bind(instance, null));
- wrapped.write(JSON.stringify(['here', 'is', 'something.']));
+ "the on() method": {
+ topic: function (outbound, inbound) {
+ outbound.on('data.}here.}is', this.callback.bind(outbound, null));
+ inbound.write(JSON.stringify(['here', 'is', 'something.']));
},
- "should split the data": function (_, data) {
+ "should handle namespaced events": function (_, data) {
assert.isArray(this.event);
assert.length(this.event, 3);
assert.isString(this.event[0]);
@@ -65,19 +62,19 @@ vows.describe('nssocket').addBatch({
assert.equal(data, 'something.');
},
"once idle": {
- topic: function (_, instance, wrapped) {
- instance.once('idle', this.callback.bind(null, null, instance, wrapped));
- instance.setIdle(100);
+ topic: function (_, outbound, inbound) {
+ outbound.once('idle', this.callback.bind(null, null, outbound, inbound));
+ outbound.setIdle(100);
},
- "it should emit `idle`": function (_, instance, wrapped) {
+ "it should emit `idle`": function (_, outbound, inbound) {
assert.isNull(_);
},
"the send() method": {
- topic: function (instance, wrapped) {
- wrapped.on('data', this.callback.bind(null, null, instance, wrapped));
- instance.send(['hello','world'], { some: "json", data: 123 });
+ topic: function (outbound, inbound) {
+ inbound.on('data', this.callback.bind(null, null, outbound, inbound));
+ outbound.send(['hello','world'], { some: "json", data: 123 });
},
- "we should see it on the other end": function (_, instance, wraped, data) {
+ "we should see it on the other end": function (_, outbound, wraped, data) {
assert.isObject(data);
arr = JSON.parse(data.toString());
assert.length(arr, 3);
@@ -86,9 +83,9 @@ vows.describe('nssocket').addBatch({
assert.deepEqual(arr[2], { some: "json", data: 123 });
},
"the end() method": {
- topic: function (instance, wrapped) {
- instance.on('close', this.callback.bind(null, null, instance, wrapped));
- wrapped.end();
+ topic: function (outbound, inbound) {
+ outbound.on('close', this.callback.bind(null, null, outbound, inbound));
+ inbound.end();
},
"should close without errors": function (_, _, _, err) {
assert.isUndefined(err);
View
116 test/tls-test.js
@@ -1,32 +1,28 @@
/*
* nssocket-test.js : namespace socket unit test for TLS.
*
- * (C) 2011, Nodejitsu Inc.
+ * (C) 2011, Nodejitsu Inc.
*
*/
-var fs = require('fs'),
+var assert = require('assert'),
+ fs = require('fs'),
+ net = require('net'),
path = require('path'),
- assert = require('assert'),
- spawn = require('child_process').spawn,
- vows = require('vows'),
tls = require('tls'),
- NsSocket = require('../lib/nssocket').NsSocket,
- helper = require('./helper');
+ vows = require('vows'),
+ NsSocket = require('../lib/nssocket').NsSocket;
var TLS_PORT = 50305,
- CA_NAME = 'snake-oil';
+ fixturesDir = path.join(__dirname, 'fixtures');
var serverOpts = {
- key: fs.readFileSync(path.join(__dirname, 'CA', CA_NAME+'-key.pem')),
- cert: fs.readFileSync(path.join(__dirname, 'CA', CA_NAME+'-cert.pem')),
- //ca: fs.readFileSync(conf.tls.ca),
- requestCert: true,
- rejectUnauthorized: false
+ key: fs.readFileSync(path.join(fixturesDir, 'ryans-key.pem')),
+ cert: fs.readFileSync(path.join(fixturesDir, 'ryans-cert.pem')),
+ ca: fs.readFileSync(path.join(fixturesDir, 'ryans-csr.pem'))
};
-var tlsSocket = helper.createTlsSocket(serverOpts),
- tlsServer = tls.createServer(serverOpts),
+var tlsServer = tls.createServer(serverOpts),
tlsOpt;
tlsOpt = {
@@ -35,58 +31,72 @@ tlsOpt = {
};
tlsServer.listen(TLS_PORT);
-tlsServer.on('listening', function () {
- console.dir('wtf fuuuu');
-})
vows.describe('nssocket').addBatch({
"When using NsSocket with TLS": {
- topic: new NsSocket(tlsSocket, tlsOpt),
- "should create a wrapped socket": function (instance) {
- assert.instanceOf(instance, NsSocket);
+ topic: new NsSocket(tlsOpt),
+ "should create a wrapped socket": function (outbound) {
+ assert.instanceOf(outbound, NsSocket);
},
- "that has the proper configuration settings": function (instance) {
- assert.equal(instance._type, tlsOpt.type);
- assert.equal(instance._delimiter, tlsOpt.delimiter);
+ "should have the proper configuration settings": function (outbound) {
+ assert.equal(outbound._type, tlsOpt.type);
+ assert.equal(outbound._delimiter, tlsOpt.delimiter);
},
"the connect() method": {
- topic: function (instance) {
+ topic: function (outbound) {
var that = this;
- console.dir('here first?');
- tlsServer.on('secureConnection', this.callback.bind(null, null, instance));
- instance.connect(TLS_PORT);
+ tlsServer.on('secureConnection', this.callback.bind(null, null, outbound));
+ outbound.connect(TLS_PORT);
},
- "it should actually connect": function (_, instance, wrapped) {
- assert.instanceOf(instance, NsSocket);
- assert.isTrue(!!wrapped.authorized);
+ "should actually connect": function (_, outbound, inbound) {
+ assert.instanceOf(outbound, NsSocket);
+ if (!inbound.authorized) {
+ console.log('Certificate is not authorized: ' + inbound.authorizationError);
+ }
},
- "and if we were to send data on it": {
- topic: function (socket, s) {
- socket.on('data::here::is', this.callback.bind(null, null));
- s.write('here::is::something::');
+ "the on() method": {
+ topic: function (outbound, inbound) {
+ outbound.on(['data', 'here', 'is'], this.callback.bind(outbound, null));
+ inbound.write(JSON.stringify(['here', 'is', 'something']));
},
- "we should see it show up with the delimiter": function (_, datas) {
- assert.isArray(datas);
- assert.length(datas, 3);
- assert.isString(datas[0]);
- assert.isString(datas[1]);
- assert.isString(datas[2]);
- assert.equal(datas[1], 'is');
+ "should handle namespaced events": function (_, data) {
+ assert.isString(data);
+ assert.isArray(this.event);
+ assert.length(this.event, 3);
+ assert.equal(this.event[0], 'data');
+ assert.equal(this.event[1], 'here');
+ assert.equal(this.event[2], 'is');
+ assert.equal(data, 'something');
},
- "and if we were to set it to idle": {
- topic: function (_, _, socket, s) {
- socket.once('idle', this.callback.bind(null, null, socket, s));
- socket.setIdle(100);
+ "once idle": {
+ topic: function (_, outbound, inbound) {
+ outbound.once('idle', this.callback.bind(null, null, outbound, inbound));
+ outbound.setIdle(100);
},
- "socket emits `idle` event": function (_, socket, s) {
+ "it should emit `idle`": function (_, outbound, inbound) {
+ assert.isNull(_);
},
- "and if we were to close the socket": {
- topic: function (socket, s) {
- socket.on('close', this.callback.bind(null, null, socket, s));
- s.end();
+ "the send() method": {
+ topic: function (outbound, inbound) {
+ inbound.on('data', this.callback.bind(null, null, outbound, inbound));
+ outbound.send(['hello','world'], { some: "json", data: 123 });
+ },
+ "we should see it on the other end": function (_, outbound, inbound, data) {
+ assert.isObject(data);
+ arr = JSON.parse(data.toString());
+ assert.length(arr, 3);
+ assert.equal(arr[0], 'hello');
+ assert.equal(arr[1], 'world');
+ assert.deepEqual(arr[2], { some: "json", data: 123 });
},
- "we should see it close": function (_, socket, s) {
- //
+ "the end() method": {
+ topic: function (outbound, inbound) {
+ outbound.on('close', this.callback.bind(null, null, outbound, inbound));
+ inbound.end();
+ },
+ "should close without errors": function (_, _, _, err) {
+ assert.isUndefined(err);
+ }
}
}
}
Please sign in to comment.
Something went wrong with that request. Please try again.