Add socketTimeout to settings.js for TCP server sockets

Fixes #125
adds an optional socketTimeout param to settings.js file to add a TCP server
socket timeout. Default is no timeout.
This commit is contained in:
Dave C-J 2013-12-24 13:12:17 +00:00
parent a9668a1999
commit 2ba5e0fe3e
2 changed files with 143 additions and 140 deletions

View File

@ -16,12 +16,11 @@
var RED = require(process.env.NODE_RED_HOME+"/red/red"); var RED = require(process.env.NODE_RED_HOME+"/red/red");
var reconnectTime = RED.settings.socketReconnectTime||10000; var reconnectTime = RED.settings.socketReconnectTime||10000;
var socketTimeout = RED.settings.socketTimeout||null;
var net = require('net'); var net = require('net');
var connectionPool = {}; var connectionPool = {};
function TcpIn(n) { function TcpIn(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.host = n.host; this.host = n.host;
@ -43,55 +42,53 @@ function TcpIn(n) {
node.log("connecting to "+node.host+":"+node.port); node.log("connecting to "+node.host+":"+node.port);
var id = (1+Math.random()*4294967295).toString(16); var id = (1+Math.random()*4294967295).toString(16);
client = net.connect(node.port, node.host, function() { client = net.connect(node.port, node.host, function() {
buffer = (node.datatype == 'buffer')? new Buffer(0):""; buffer = (node.datatype == 'buffer')? new Buffer(0):"";
node.log("connected to "+node.host+":"+node.port); node.log("connected to "+node.host+":"+node.port);
}); });
connectionPool[id] = client; connectionPool[id] = client;
client.on('data', function (data) { client.on('data', function (data) {
if (node.datatype != 'buffer') { if (node.datatype != 'buffer') {
data = data.toString(node.datatype); data = data.toString(node.datatype);
} }
if (node.stream) { if (node.stream) {
if ((node.datatype) === "utf8" && node.newline != "") { if ((node.datatype) === "utf8" && node.newline != "") {
buffer = buffer+data; buffer = buffer+data;
var parts = buffer.split(node.newline); var parts = buffer.split(node.newline);
for (var i = 0;i<parts.length-1;i+=1) { for (var i = 0;i<parts.length-1;i+=1) {
var msg = {topic:node.topic, payload:parts[i]}; var msg = {topic:node.topic, payload:parts[i]};
msg._session = {type:"tcp",id:id};
node.send(msg);
}
buffer = parts[parts.length-1];
} else {
var msg = {topic:node.topic, payload:data};
msg._session = {type:"tcp",id:id}; msg._session = {type:"tcp",id:id};
node.send(msg); node.send(msg);
} }
buffer = parts[parts.length-1];
} else { } else {
if ((typeof data) === "string") { var msg = {topic:node.topic, payload:data};
buffer = buffer+data;
} else {
buffer = Buffer.concat([buffer,data],buffer.length+data.length);
}
}
});
client.on('end', function() {
if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
var msg = {topic:node.topic,payload:buffer};
msg._session = {type:"tcp",id:id}; msg._session = {type:"tcp",id:id};
node.send(msg); node.send(msg);
buffer = null;
} }
} else {
if ((typeof data) === "string") {
buffer = buffer+data;
} else {
buffer = Buffer.concat([buffer,data],buffer.length+data.length);
}
}
});
client.on('end', function() {
if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
var msg = {topic:node.topic,payload:buffer};
msg._session = {type:"tcp",id:id};
node.send(msg);
buffer = null;
}
}); });
client.on('close', function() { client.on('close', function() {
delete connectionPool[id]; delete connectionPool[id];
node.log("connection lost to "+node.host+":"+node.port); node.log("connection lost to "+node.host+":"+node.port);
if (!node.closing) { if (!node.closing) {
reconnectTimeout = setTimeout(setupTcpClient, reconnectTime); reconnectTimeout = setTimeout(setupTcpClient, reconnectTime);
} }
}); });
client.on('error', function(err) { client.on('error', function(err) {
node.log(err); node.log(err);
}); });
@ -105,52 +102,57 @@ function TcpIn(n) {
}); });
} else { } else {
var server = net.createServer(function (socket) { var server = net.createServer(function (socket) {
var id = (1+Math.random()*4294967295).toString(16); if (socketTimeout !== null) { socket.setTimeout(socketTimeout); }
connectionPool[id] = socket; var id = (1+Math.random()*4294967295).toString(16);
connectionPool[id] = socket;
var buffer = (node.datatype == 'buffer')? new Buffer(0):"";
socket.on('data', function (data) {
if (node.datatype != 'buffer') {
data = data.toString(node.datatype);
}
if (node.stream) { var buffer = (node.datatype == 'buffer')? new Buffer(0):"";
if ((typeof data) === "string" && node.newline != "") { socket.on('data', function (data) {
buffer = buffer+data; if (node.datatype != 'buffer') {
var parts = buffer.split(node.newline); data = data.toString(node.datatype);
for (var i = 0;i<parts.length-1;i+=1) { }
var msg = {topic:node.topic, payload:parts[i],ip:socket.remoteAddress,port:socket.remotePort};
msg._session = {type:"tcp",id:id}; if (node.stream) {
node.send(msg); if ((typeof data) === "string" && node.newline != "") {
} buffer = buffer+data;
buffer = parts[parts.length-1]; var parts = buffer.split(node.newline);
} else { for (var i = 0;i<parts.length-1;i+=1) {
var msg = {topic:node.topic, payload:data}; var msg = {topic:node.topic, payload:parts[i],ip:socket.remoteAddress,port:socket.remotePort};
msg._session = {type:"tcp",id:id};
node.send(msg);
}
} else {
if ((typeof data) === "string") {
buffer = buffer+data;
} else {
buffer = Buffer.concat([buffer,data],buffer.length+data.length);
}
}
});
socket.on('end', function() {
if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
var msg = {topic:node.topic,payload:buffer};
msg._session = {type:"tcp",id:id}; msg._session = {type:"tcp",id:id};
node.send(msg); node.send(msg);
buffer = null;
} }
}); buffer = parts[parts.length-1];
socket.on('close', function() { } else {
delete connectionPool[id]; var msg = {topic:node.topic, payload:data};
}); msg._session = {type:"tcp",id:id};
socket.on('error',function(err) { node.send(msg);
node.log(err); }
}); } else {
if ((typeof data) === "string") {
buffer = buffer+data;
} else {
buffer = Buffer.concat([buffer,data],buffer.length+data.length);
}
}
});
socket.on('end', function() {
if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
var msg = {topic:node.topic,payload:buffer};
msg._session = {type:"tcp",id:id};
node.send(msg);
buffer = null;
}
});
socket.on('timeout', function() {
node.log('timeout closed socket port '+node.port);
socket.end();
});
socket.on('close', function() {
delete connectionPool[id];
});
socket.on('error',function(err) {
node.log(err);
});
}); });
server.listen(node.port); server.listen(node.port);
node.log('listening on port '+node.port); node.log('listening on port '+node.port);
@ -163,7 +165,6 @@ function TcpIn(n) {
} }
} }
RED.nodes.registerType("tcp in",TcpIn); RED.nodes.registerType("tcp in",TcpIn);
function TcpOut(n) { function TcpOut(n) {
@ -180,51 +181,47 @@ function TcpOut(n) {
var reconnectTimeout; var reconnectTimeout;
var client = null; var client = null;
var connected = false; var connected = false;
function setupTcpClient() { function setupTcpClient() {
node.log("connecting to "+node.host+":"+node.port); node.log("connecting to "+node.host+":"+node.port);
client = net.connect(node.port, node.host, function() { client = net.connect(node.port, node.host, function() {
connected = true; connected = true;
node.log("connected to "+node.host+":"+node.port); node.log("connected to "+node.host+":"+node.port);
}); });
client.on('error', function (err) { client.on('error', function (err) {
node.log('error : '+err); node.log('error : '+err);
}); });
client.on('end', function (err) { client.on('end', function (err) {
}); });
client.on('close', function() { client.on('close', function() {
node.log("connection lost to "+node.host+":"+node.port); node.log("connection lost to "+node.host+":"+node.port);
connected = false; connected = false;
client.destroy(); client.destroy();
if (!node.closing) { if (!node.closing) {
reconnectTimeout = setTimeout(setupTcpClient,reconnectTime); reconnectTimeout = setTimeout(setupTcpClient,reconnectTime);
} }
}); });
} }
setupTcpClient(); setupTcpClient();
node.on("input", function(msg) { node.on("input", function(msg) {
if (connected && msg.payload != null) { if (connected && msg.payload != null) {
if (Buffer.isBuffer(msg.payload)) { if (Buffer.isBuffer(msg.payload)) {
client.write(msg.payload); client.write(msg.payload);
} else if (typeof msg.payload === "string" && node.base64) { } else if (typeof msg.payload === "string" && node.base64) {
client.write(new Buffer(msg.payload,'base64')); client.write(new Buffer(msg.payload,'base64'));
} else { } else {
client.write(new Buffer(""+msg.payload)); client.write(new Buffer(""+msg.payload));
}
} }
}
}); });
node.on("close", function() { node.on("close", function() {
this.closing = true; this.closing = true;
client.end(); client.end();
clearTimeout(reconnectTimeout); clearTimeout(reconnectTimeout);
}); });
} else if (node.beserver == "reply") { } else if (node.beserver == "reply") {
node.on("input",function(msg) { node.on("input",function(msg) {
if (msg._session && msg._session.type == "tcp") { if (msg._session && msg._session.type == "tcp") {
@ -243,33 +240,37 @@ function TcpOut(n) {
} else { } else {
var connectedSockets = []; var connectedSockets = [];
var server = net.createServer(function (socket) { var server = net.createServer(function (socket) {
var remoteDetails = socket.remoteAddress+":"+socket.remotePort; if (socketTimeout !== null) { socket.setTimeout(socketTimeout); }
node.log("connection from "+remoteDetails); var remoteDetails = socket.remoteAddress+":"+socket.remotePort;
connectedSockets.push(socket); node.log("connection from "+remoteDetails);
socket.on('close',function() { connectedSockets.push(socket);
node.log("connection closed from "+remoteDetails); socket.on('timeout', function() {
connectedSockets.splice(connectedSockets.indexOf(socket),1); node.log('timeout closed socket port '+node.port);
}); socket.end();
socket.on('error',function() { });
node.log("socket error from "+remoteDetails); socket.on('close',function() {
connectedSockets.splice(connectedSockets.indexOf(socket),1); node.log("connection closed from "+remoteDetails);
}); connectedSockets.splice(connectedSockets.indexOf(socket),1);
});
socket.on('error',function() {
node.log("socket error from "+remoteDetails);
connectedSockets.splice(connectedSockets.indexOf(socket),1);
});
}); });
node.on("input", function(msg) { node.on("input", function(msg) {
if (msg.payload != null) { if (msg.payload != null) {
var buffer; var buffer;
if (Buffer.isBuffer(msg.payload)) { if (Buffer.isBuffer(msg.payload)) {
buffer = msg.payload; buffer = msg.payload;
} else if (typeof msg.payload === "string" && node.base64) { } else if (typeof msg.payload === "string" && node.base64) {
buffer = new Buffer(msg.payload,'base64'); buffer = new Buffer(msg.payload,'base64');
} else { } else {
buffer = new Buffer(""+msg.payload); buffer = new Buffer(""+msg.payload);
}
for (var i = 0; i<connectedSockets.length;i+=1) {
connectedSockets[i].write(buffer);
}
} }
for (var i = 0; i<connectedSockets.length;i+=1) {
connectedSockets[i].write(buffer);
}
}
}); });
server.listen(node.port); server.listen(node.port);
@ -283,5 +284,3 @@ function TcpOut(n) {
} }
RED.nodes.registerType("tcp out",TcpOut); RED.nodes.registerType("tcp out",TcpOut);

View File

@ -16,12 +16,12 @@
module.exports = { module.exports = {
// the tcp port that the Node-RED web server is listening on // the tcp port that the Node-RED web server is listening on
uiPort: 1880, uiPort: 1880,
// By default, the Node-RED UI accepts connections on all IPv4 interfaces. // By default, the Node-RED UI accepts connections on all IPv4 interfaces.
// The following property can be used to listen on a specific interface. For // The following property can be used to listen on a specific interface. For
// example, the following would only allow connections from the local machine. // example, the following would only allow connections from the local machine.
//uiHost: "127.0.0.1", //uiHost: "127.0.0.1",
// Retry time in milliseconds for MQTT connections // Retry time in milliseconds for MQTT connections
mqttReconnectTime: 15000, mqttReconnectTime: 15000,
@ -31,20 +31,24 @@ module.exports = {
// Retry time in milliseconds for TCP socket connections // Retry time in milliseconds for TCP socket connections
//socketReconnectTime: 10000, //socketReconnectTime: 10000,
// Timeout in milliseconds for TCP server socket connections
// defaults to no timeout
//socketTimeout: 120000,
// Maximum number of lines in debug window before pruning // Maximum number of lines in debug window before pruning
debugMaxLength: 1000, debugMaxLength: 1000,
// The file containing the flows. If not set, it defaults to flows_<hostname>.json // The file containing the flows. If not set, it defaults to flows_<hostname>.json
//flowFile: 'flows.json', //flowFile: 'flows.json',
// By default, all user data is stored in the Node-RED install directory. To // By default, all user data is stored in the Node-RED install directory. To
// use a different location, the following property can be used // use a different location, the following property can be used
//userDir: '/home/nol/.node-red/', //userDir: '/home/nol/.node-red/',
// Node-RED scans the `nodes` directory in the install directory to find nodes. // Node-RED scans the `nodes` directory in the install directory to find nodes.
// The following property can be used to specify an additional directory to scan. // The following property can be used to specify an additional directory to scan.
//nodesDir: '/home/nol/.node-red/nodes', //nodesDir: '/home/nol/.node-red/nodes',
// You can protect the user interface with a userid and password by using the following property // You can protect the user interface with a userid and password by using the following property
// the password must be an md5 hash eg.. 5f4dcc3b5aa765d61d8327deb882cf99 ('password') // the password must be an md5 hash eg.. 5f4dcc3b5aa765d61d8327deb882cf99 ('password')
//httpAuth: {user:"user",pass:"5f4dcc3b5aa765d61d8327deb882cf99"}, //httpAuth: {user:"user",pass:"5f4dcc3b5aa765d61d8327deb882cf99"},
@ -53,11 +57,11 @@ module.exports = {
// The following property can be used to specifiy a different root path. // The following property can be used to specifiy a different root path.
//httpRoot: '/admin', //httpRoot: '/admin',
// When httpRoot is used to move the UI to a different root path, the // When httpRoot is used to move the UI to a different root path, the
// following property can be used to identify a directory of static content // following property can be used to identify a directory of static content
// that should be served at http://localhost:1880/. // that should be served at http://localhost:1880/.
//httpStatic: '/home/nol/node-red-dashboard/', //httpStatic: '/home/nol/node-red-dashboard/',
// The following property can be used to enable HTTPS // The following property can be used to enable HTTPS
// See http://nodejs.org/api/https.html#https_https_createserver_options_requestlistener // See http://nodejs.org/api/https.html#https_https_createserver_options_requestlistener
// for details on its contents. // for details on its contents.