前段时间做一个Node.js应用时,需要分配一些端口,由于没什么时间细想,只是用一系列连续而且数字比较大的端口。
下来这段来自netutil的findFreePort以后可以一看。其本质上就是在一段区间随便找一个port,先试一把,行则OK,不行则再来.
var net = require("net");var exec = require("child_process").exec;exports.findFreePort = function(start, end, hostname, callback) { var pivot = Math.floor(Math.random() * (end-start)) + start; var port = pivot; asyncRepeat(function(next, done) { var stream = net.createConnection(port, hostname); stream.on("connect", function() { stream.destroy(); port++; if (port > end) port = start; if (port == pivot) done("Could not find free port."); next(); }); stream.on("error", function() { done(); }); }, function(err) { callback(err, port); });};exports.isPortOpen = function(hostname, port, timeout, callback) { var stream = net.createConnection(port, hostname); stream.on("connect", function() { clearTimeout(id); stream.destroy(); callback(true); }); stream.on("error", function() { clearTimeout(id); stream.destroy(); callback(false); }); var id = setTimeout(function() { stream.destroy(); callback(false); }, timeout || 1000);};exports.getHostName = function(callback) { exec("hostname", function (error, stdout, stderr) { if (error) return callback(stderr); callback(null, stdout.toString().split("\n")[0]); });};function asyncRepeat(callback, onDone) { callback(function() { asyncRepeat(callback, onDone); }, onDone);}