Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianseilund committed Dec 1, 2012
1 parent dc41562 commit 3568d6a
Show file tree
Hide file tree
Showing 11 changed files with 572 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/.idea
/node_modules
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2012 Sebastian Seilund

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
node-json-socket
================
================

- Decorator
157 changes: 157 additions & 0 deletions lib/json-socket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
var net = require('net');

var JsonSocket = function(socket) {
this._socket = socket;
this._contentLength = null;
this._buffer = '';
this._closed = false;
socket.on('data', this._onData.bind(this));
socket.on('close', this._onClose.bind(this));
socket.on('err', this._onError.bind(this));
};
module.exports = JsonSocket;

JsonSocket.sendSingleMessage = function(port, host, message, callback) {
callback = callback || function(){};
var socket = new JsonSocket(new net.Socket());
socket.connect(port, host);
socket.on('error', function(err) {
callback(err);
});
socket.on('connect', function() {
socket.sendEndMessage(message, callback);
});
};

JsonSocket.sendSingleMessageAndReceive = function(port, host, message, callback) {
callback = callback || function(){};
var socket = new JsonSocket(new net.Socket());
socket.connect(port, host);
socket.on('error', function(err) {
callback(err);
});
socket.on('connect', function() {
socket.sendMessage(message, function(err) {
if (err) {
socket.end();
return callback(err);
}
socket.on('message', function(message) {
socket.end();
callback(null, message)
});
});
});
};

JsonSocket.prototype = {

_onData: function(data) {
data = data.toString();
try {
this._handleData(data);
} catch (e) {
this.sendError(e);
}
},
_handleData: function(data) {
this._buffer += data;
if (this._contentLength == null) {
var i = this._buffer.indexOf('#');
//Check if the buffer has a #, if not, the end of the buffer string might be in the middle of a content length string
if (i !== -1) {
var rawContentLength = this._buffer.substring(0, i);
this._contentLength = parseInt(rawContentLength);
if (isNaN(this._contentLength)) {
this._contentLength = null;
this._buffer = '';
var err = new Error('Invalid content length supplied ('+rawContentLength+') in: '+this._buffer);
err.code = 'E_INVALID_CONTENT_LENGTH';
throw err;
}
this._buffer = this._buffer.substring(i+1);
}
}
if (this._contentLength != null) {
if (this._buffer.length == this._contentLength) {
this._handleMessage(this._buffer);
} else if (this._buffer.length > this._contentLength) {
var message = this._buffer.substring(0, this._contentLength);
var rest = this._buffer.substring(this._contentLength);
this._handleMessage(message);
this._onData(rest);
}
}
},
_handleMessage: function(data) {
this._contentLength = null;
this._buffer = '';
var message;
try {
message = JSON.parse(data);
} catch (e) {
var err = new Error('Could not parse JSON: '+e.message+'\nRequest data: '+data);
err.code = 'E_INVALID_JSON';
throw err;
}
message = message || {};
this._socket.emit('message', message);
},

sendError: function(err) {
this.sendMessage(this._formatError(err));
},
sendEndError: function(err) {
this.sendEndMessage(this._formatError(err));
},
_formatError: function(err) {
return {success: false, error: err.toString()};
},

sendMessage: function(message, callback) {
if (this._closed) {
if (callback) {
callback(new Error('The socket is closed.'));
}
return;
}
this._socket.write(this._formatMessageData(message), 'utf-8', callback);
},
sendEndMessage: function(message, callback) {
var that = this;
this.sendMessage(message, function(err) {
that.end();
if (callback) {
if (err) return callback(err);
callback();
}
});
},
_formatMessageData: function(message) {
var messageData = JSON.stringify(message);
var data = messageData.length + '#' + messageData;
return data;
},

_onClose: function() {
this._closed = true;
},
_onError: function() {
this._closed = true;
},
isClosed: function() {
return this._closed;
}

};

var delegates = [
'connect',
'on',
'end'
];
delegates.forEach(function(method) {
JsonSocket.prototype[method] = function() {
this._socket[method].apply(this._socket, arguments);
}
});
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "json-socket",
"description": "Write me...",
"main": "./lib/json-socket",
"author": "Sebastian Seilund",
"version": "0.1.1",
"repository" : {
"type" : "git",
"url" : "http://github.com/sebastianseilund/node-json-socket.git"
},
"bugs" : {
"url" : "http://github.com/sebastianseilund/node-json-socket/issues"
},
"maintainers": [{
"name": "Sebastian Seilund",
"email": "sebastian@seilund.com",
"url": "http://www.sebastianseilund.com"
}],
"licenses" : [
{
"type" : "MIT",
"url" : "http://github.com/sebastianseilund/node-json-socket/raw/master/LICENSE"
}
],
"devDependencies": {
"mocha": "*"
},
"dependencies": {
"async": "0.1.x"
},
"scripts": {
"test": "./node_modules/.bin/mocha $(shell find test -name '*.test.js')"
}
}
128 changes: 128 additions & 0 deletions test/connection.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
var assert = require('assert'),
async = require('async'),
JsonSocket = require('../lib/json-socket'),
helpers = require('./helpers');

describe('JsonSocket connection', function() {

it('should connect, send and receive message', function(callback) {
helpers.createServerAndClient(function(err, server, clientSocket, serverSocket) {
if (err) return callback(err);
assert.equal(clientSocket.isClosed(), false);
assert.equal(serverSocket.isClosed(), false);
async.parallel([
function(callback) {
clientSocket.sendMessage({type: 'ping'}, callback);
},
function(callback) {
clientSocket.on('message', function(message) {
assert.deepEqual(message, {type: 'pong'});
callback();
});
},
function(callback) {
serverSocket.on('message', function(message) {
assert.deepEqual(message, {type: 'ping'});
serverSocket.sendMessage({type: 'pong'}, callback);
});
}
], function(err) {
if (err) return callback(err);
assert.equal(clientSocket.isClosed(), false);
assert.equal(serverSocket.isClosed(), false);
helpers.closeServer(server, callback);
});
});
});

it('should send multiple messages', function(callback) {
helpers.createServerAndClient(function(err, server, clientSocket, serverSocket) {
if (err) return callback(err);
async.parallel([
function(callback) {
async.forEach(helpers.range(1, 100), function(i, callback) {
clientSocket.sendMessage({number: i}, callback);
}, callback);
},
function(callback) {
var lastNumber = 0;
serverSocket.on('message', function(message) {
assert.deepEqual(message.number, lastNumber + 1);
lastNumber = message.number;
if (lastNumber == 100) {
callback();
}
});
}
], function(err) {
if (err) return callback(err);
helpers.closeServer(server, callback);
});
});
});

it('should send end message', function(callback) {
helpers.createServerAndClient(function(err, server, clientSocket, serverSocket) {
if (err) return callback(err);
async.parallel([
function(callback) {
clientSocket.sendEndMessage({type: 'ping'}, function(err) {
callback(err);
});
},
function(callback) {
serverSocket.on('message', function(message) {
assert.deepEqual(message, {type: 'ping'});
setTimeout(callback, 10);
});
}
], function(err) {
if (err) return callback(err);
assert.equal(clientSocket.isClosed(), true);
assert.equal(serverSocket.isClosed(), true);
helpers.closeServer(server, callback);
});
});
});

it('should return true for isClosed() when server disconnects', function(callback) {
helpers.createServerAndClient(function(err, server, clientSocket, serverSocket) {
if (err) return callback(err);
async.series([
function(callback) {
serverSocket.end();
setTimeout(callback, 10);
},
function(callback) {
assert.equal(clientSocket.isClosed(), true);
assert.equal(serverSocket.isClosed(), true);
callback();
}
], function(err) {
if (err) return callback(err);
helpers.closeServer(server, callback);
});
});
});

it('should return true for isClosed() when client disconnects', function(callback) {
helpers.createServerAndClient(function(err, server, clientSocket, serverSocket) {
if (err) return callback(err);
async.series([
function(callback) {
clientSocket.end();
setTimeout(callback, 10);
},
function(callback) {
assert.equal(clientSocket.isClosed(), true);
assert.equal(serverSocket.isClosed(), true);
callback();
}
], function(err) {
if (err) return callback(err);
helpers.closeServer(server, callback);
});
});
});

});
Loading

0 comments on commit 3568d6a

Please sign in to comment.