Skip to content

Instantly share code, notes, and snippets.

@thiagodelgado111
Last active September 29, 2015 15:21
Show Gist options
  • Save thiagodelgado111/35b842de17c6b742c970 to your computer and use it in GitHub Desktop.
Save thiagodelgado111/35b842de17c6b742c970 to your computer and use it in GitHub Desktop.
Custom server TCP
/*jslint node: true */
var net = require('net');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var _ = require('lodash');
var S = require('string');
var traceback = require('traceback');
var dateFormat = require('date-format');
var os = require("os");
var __CR__ = String.fromCharCode(13);
(function() {
var inspect = require('util').inspect;
var emit_ = EventEmitter.prototype.emit;
EventEmitter.prototype.emit = function(name) {
var args = Array.prototype.slice.call(arguments);
if (!(this === process.stderr && name === 'drain')) {
console.error("Event '%s', arguments: %s",
name, inspect(args.slice(1), false, 1));
}
return emit_.apply(this, args);
};
})();
/**
* Class that encapsulates communication protocol
* @constructor
* @param {Object} config Configuration parameters required to start communication
*/
var CustomServer = function(config) {
/**
* Verifying if the parameters were supplied
* @param {args} arguments function arguments
*/
if (_.isNull(config) ||
_.isUndefined(config) ||
_.isEmpty(config) ||
!_.isObject(config)) {
throw new Error("Invalid socket configuration");
}
/**
* Verifies if the PORT is valid
*/
if (_.isUndefined(config.PORT) || _.isNull(config.PORT) || _.isNaN(parseInt(config.PORT, 10))) {
throw new Error("Invalid PORT configuration");
}
/**
* Socket configuration
* @type {Object}
*/
var CONFIG = {
HOST: config.HOST || "0.0.0.0",
PORT: config.PORT
};
/**
* current node with whom the socket is communicating with
* @type {Node}
*/
this.currentNode = null;
/**
* socket object
* @type {net.Socket}
*/
this.socket = null;
/**
* socket buffer
* @type {Buffer}
*/
this.socketBuffer = null;
/**
* socket Server
* @type {net.Server}
*/
this.server = null;
var self = this;
/**
* Creates a server that will listen in a given PORT
* @return {Server} server created to listen
*/
this.createConnection = function() {
console.log("CONFIGURATION: HOST [" + CONFIG.HOST + "]");
console.log("CONFIGURATION: PORT [" + CONFIG.PORT + "]");
console.log("CONFIGURATION: BEGIN GATEWAY TIMEOUT [" + CONFIG.BEGIN_GATEWAY_TIMEOUT + "]");
console.log("CONFIGURATION: UNICAST DATE TIMEOUT [" + CONFIG.UNICAST_DATA_TIMEOUT + "]");
console.log("CONFIGURATION: MODULE TIMEOUT [" + CONFIG.MODULE_TIMEOUT + "]");
console.log("CONFIGURATION: WAIT FOR DELAYED COMMAND [" + CONFIG.WAIT_FOR_DELAYED_COMMAND + "]");
this.server = net.createServer(function(sock) {
self.socket = sock;
//self.socket.setEncoding('utf8');
console.log('CONNECTED: ' + self.socket.remoteAddress + ':' + self.socket.remotePort);
self.emit('serverCreated', self.socket);
self.socket.removeAllListeners('data');
self.socket.on('data', onDataReceived);
self.socket.removeAllListeners('error');
self.socket.on('error', onError);
self.socket.removeAllListener('close');
self.socket.on('close', onSocketClosed);
});
};
/**
* Start listening for connections at the given port using "net" module
* @return {null} null
*/
this.open = function() {
console.log('SERVER STARTED AND LISTENING ON [' + CONFIG.HOST + ':' + CONFIG.PORT + ']');
this.server.listen(CONFIG.PORT, CONFIG.HOST);
return null;
};
this.begin = function(fnCallback) {
if (!!self.currentNode) {
self.currentNode.state = CONSTANTS.INITIALIZING;
}
/**
* CLEANING THE BUFFER
*/
self.socketBuffer = null;
console.log("*** WAITING BEFORE SENDING +++ COMMAND ***");
setTimeout(function() {
console.log("*** SENDING +++ ***");
self.socket.write("+++");
console.log("*** SENDING AT COMMAND ***");
self.socket.write("AT" + __CR__);
}, CONFIG.BEGIN_GATEWAY_TIMEOUT);
};
function onError(args) {
console.error(args);
}
/**
* Socket received data, emits multiple events based on the incoming data
* @param {Buffer} data Data buffer
* @return {null} null
*/
function onDataReceived(data) {
self.socketBuffer += data;
console.log('[' + self.socketBuffer + '] - [' + dateFormat('dd/MM/yyyy;hh:mm:ss', new Date()) + ']');
self.socket.write("BLA");
}
function onSocketClosed(data, socket) {
console.log('CLOSED: ');
self.emit('socketClosed', {
data: data,
socket: socket
});
self.socket = null;
return null;
}
function refreshNodeTimeoutHandle(node, timeoutMsg, timeout, socket) {
console.log("*** REFRESH TIMEOUT ***");
node.resetTimeout();
node.defineTimeout(timeoutMsg, timeout, function() {
if (!!self.socketBuffer)
self.socketBuffer = "";
self.emit('nodeCommunicationEnded')
});
}
};
util.inherits(CustomServer, EventEmitter);
module.exports = CustomServer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment