Skip to content
Browse files

Checks if the server is already open before trying to bound to the port

  • Loading branch information...
1 parent 33d17ba commit e0bb6ec57bf0c87c380f487a80db7654b9a78282 @MiguelMadero committed
Showing with 41 additions and 6 deletions.
  1. +41 −6 lib/cluster/worker.js
View
47 lib/cluster/worker.js
@@ -1,4 +1,7 @@
var fs = require('fs')
+ , net = require('net')
+ , timeout = 400
+ , sys = require("sys")
, utils = require('utilities')
, dispatch = require('./worker_dispatch')
, Logger = require('./worker_logger').Logger
@@ -71,21 +74,53 @@ Worker.prototype = new (function () {
this.startServer = function () {
if (this.config) {
var hostname = this.config.hostname || null
+ , self = this
+ , port = parseInt(this.config.port, 10)
, ssl = this.config.ssl ? ' (SSL)' : ''
, spdy = this.config.spdy ? '(SPDY)' : '';
- this.server.listen(parseInt(this.config.port, 10), hostname);
-
- this.log.info('Server worker running in ' + this.config.environment +
- ' on port ' + this.config.port + ssl + spdy + ' with a PID of: ' + process.pid);
- this.log.debug('LOGGING STARTED ============================================');
- this.log.debug('============================================================');
+ this.isOpen(port, hostname, function (isOpen) {
+ if (isOpen) {
+ console.log("The port " + port + " is already in use.");
+ }
+ else{
+ self.server.listen(port, hostname, function () {
+
+ self.log.info('Server worker running in ' + self.config.environment +
+ ' on port ' + self.config.port + ssl + spdy + ' with a PID of: ' + process.pid);
+ self.log.debug('LOGGING STARTED ============================================');
+ self.log.debug('============================================================');
+ });
+ }
+ });
}
else {
this.log.error('Cannot start server without config.');
}
};
+ this.isOpen = function (port, host, callback) {
+ var isOpen = false;
+ var conn = net.createConnection(port, host);
+
+ var timeoutId = setTimeout(function() {onClose();}, timeout);
+ var onClose = function() {
+ clearTimeout(timeoutId);
+ delete conn;
+ callback(isOpen, port, host);
+ };
+
+ var onOpen = function() {
+ isOpen = true;
+ //console.log(host+":"+port+" is taken");
+ conn.end();
+ };
+
+ conn.on('close', onClose);
+ conn.on('error', function() {conn.end();});
+ conn.on('connect', onOpen);
+}
+
this.configure = function (config) {
this.config = config;
this._afterConfigure();

0 comments on commit e0bb6ec

Please sign in to comment.
Something went wrong with that request. Please try again.