检查某个端口是否被占用
@param {Number} port 端口号，取值为 >= 0 and < 65536
@param {Function} [callback] 回调，接受两个参数，isSuccess 和 err
337483
function portIsOccupied(port, callback) {
    // 创建服务并监听该端口
    const server = net.createServer().listen(port);

    server.on('listening', function () { // 执行这块代码说明端口未被占用
        server.close(); // 关闭服务
        // console.log('The port【' + port + '】 is available.'); // 控制台输出信息

        if (typeof callback === 'function') {
            callback(true);
        }
    });

    server.on('error', function (err) {
        if (err.code === 'EADDRINUSE') { // 端口已经被使用
            // console.log('The port【' + port + '】 is occupied, please change other port.');
        }

        if (typeof callback === 'function') {
            callback(false, err);
        }
    });
}
66913
def port(self, port):
        
        if not isinstance(port, int):
            raise WebDriverException("Port needs to be an integer")
        try:
            port = int(port)
            if port < 1 or port > 65535:
                raise WebDriverException("Port number must be in the range 1..65535")
        except (ValueError, TypeError):
            raise WebDriverException("Port needs to be an integer")
        self._port = port
        self.set_preference("webdriver_firefox_port", self._port)
719379
function(callback) {
        var scarlet = new Scarlet(Math.min(opts.n, 100));

        function connect(taskObject) {
            var client = taskObject.task.client;
            var i = taskObject.task.idx;

            client.connect(function() {
                scarlet.taskDone(taskObject);
            });

            client.on("error", function(err) {
                console.log(err + ": Client " + i);
            });
        }

        console.time("Connect");

        // if mode is `clients`, we create (opts.complicating) clients,
        // otherwise we create only one.
        var max = opts["complicating-mode"] === "clients" ? opts.complicating : 1;
        for(var i = 0; i < max; i++) {
            var client = illyria2.createClient("127.0.0.1", SERVER_PORT, {
                runTimeout: 10000,
                retryInterval: 1000,
                reconnect: true
            });

            scarlet.push({ idx: i, client: client }, connect);

            clients.push(client);
        }

        scarlet.afterFinish(max, function() {
            console.timeEnd("Connect");
            callback();
        }, false);
    }
615475
def remove_port_callback(self, port, cb):
        """"""
        logger.debug('Removing callback on port [%d] to [%s]', port, cb)
        for port_callback in self.cb:
            if port_callback.port == port and port_callback.callback == cb:
                self.cb.remove(port_callback)
592438
protected int getAutoPort(int port) throws BindException {
		if (System.getProperty("os.name").startsWith("Mac")) {
			if (port == 80) {
				port = 8080;
			}
			return port;
		}
		try {
			checkOpened(port);
		}
		catch (BindException e) {
			if (port == 80) {
				checkOpened(8080);
				port = 8080;
			}
			else {
				throw e;
			}
		}
		return port;
	}
1066831
def check_port(helper, port):
    
    try:
        int(port)
    except ValueError:
        helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='')
986052
function(callback){
        if(source['brokerId']!='null'){
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                mqttHost = result[0]['ipAddress'];
                mqttPort = result[0]['port'];
                console.log(result);
            });
        }else{
            mqttHost = mqttPort = null;
        }
    }
628320
function normalizePort(val, def=3000) {
    var port = parseInt(val, 10);

    // named pipe
    if (isNaN(port)) return val;

    // port number
    if (port >= 0) return port;

    return def;
}
802479
function findPort(cb) {
    var port = tryPort;
    tryPort += 1;

    var server = net.createServer();
    server.listen(port, function(err) {
        server.once('close', function() {
            cb(port);
        });
        server.close();
    });
    server.on('error', function(err) {
        log("port " + tryPort + " is occupied");
        findPort(cb);
    });
}
980180
function(selectedPort, callback) {
        if(selectedPort === false)
          grunt.fatal('No available port was found')

        self.data.targets.forEach(function(prop) {
          pp.injectPort(prop, selectedPort)
        })

        if(pp.options.name) {
          pp.injectPort(pp.options.name, selectedPort)
        }

        callback(null)
        return
      }
504787
function (port, protocol) {
        var portRegex = this._matchPatternObject.port,

            // default port for given protocol
            defaultPort = protocol && DEFAULT_PROTOCOL_PORT[protocol];

        // return true if both given port and match pattern are absent
        if (typeof port === UNDEFINED && typeof portRegex === UNDEFINED) {
            return true;
        }

        // convert integer port to string
        (port && typeof port !== STRING) && (port = String(port));

        // assign default port or portRegex
        !port && (port = defaultPort);
        !portRegex && (portRegex = defaultPort);

        // matches * or specific port
        return (
            portRegex === MATCH_ALL ||
            portRegex === port
        );
    }
1196699
function() {
	this.ENL_PORT = 3610;
	this.BAUD = 115200;
	this.SERIAL_SEND_INTERVAL = 500; // ms

	this.initialized = false;
	this.dataCallback = function(){};
	this.sentCallback = function(){};
	this.dataCallbackSerial = function(){};
	this.sentCallbackSerial = function(){};

	this.serialCallback = function(){};
	this.params = {};
	this.port = null;
	this.device = null;
	this.is_discovering = false;
	this.discovery_timer_id = null;
	this.response_buffer = null;
	this.response_text = '';

	this.mAdapter = null;
}
1344737
def port(self, value):
        

        if value is not None:
            assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format(
                "port", value)
            assert type(value) >= 0 and type(value) >= 65535, \
                "'{0}' attribute: '{1}' value must be in 0-65535 range!".format("port", value)
        self.__port = value
714912
function probeServer(address, port, callback) {
    address = address || 'localhost';
    port    = port || 443;

    pingServer({
        address:  address,
        port:     port,
        attempts: 1,
        timeout:  5000
    }, function(err, data) {
        var available = data.min !== undefined;
        callback(err, available);
    });
}
581890
function(res) {
    res.setEncoding('utf8');
    var data = "";
    res.on('data', function(chunk) {
      data+=chunk;
    });

    res.on('end', function() {
      // Get HTTP Statuscode and act according to situation
      var code = res.statusCode;
      try { // try to parse JSON
        var answer = JSON.parse(data);
      } catch (e) {
        var err = {};
        err.http_code = 500;
        err.message = "No valid JSON received: "+data;
        callback(err, null);
        return;
      }
      if(code >= 200 && code <= 206) { // request was successful
        callback(null, answer);
      } else if (code >= 300 && code <= 307) { // server send redirect
        // we do not follow anything the server wants us to follow right now, since this should never be the case.
        // instead let's raise an error.
        var err = new Object();
        err.http_code = 500;
        err.message = "Redirects not supported by pastyclient-node"
        callback(err, null);
      } else if (code >= 400 && code <= 418) { // client error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else if(answer.code != undefined && answer.message != undefined) { // New RestError, temporary support both 
          var err = answer;
          err.http_code = code;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Resource not found";
        }
        callback(err, null);
      } else if (code >= 500 && code <= 505) { // server error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Internal Server Error";
        }
        callback(err, null);
      } else {
        // Not existant HTTP code. Raise error.
        var err = new Object();
        err.http_code = 500;
        err.message = "HTTP Status Code "+code+" is not supported by pastyclient-node"
        callback(err, null);
      }
    });
  }
142276
function(callback)
    {
        var params = util.extend({count:1}, this.params);        
        this.api.doRequest("GET", this.path, params, function(err, res) {
            if (err)
            {
                return callback(err);
            }                    
            callback(null, res.count);
        });
    }
8689
function(url) {
		var ports = { // we ignore default ports
			http: 80,
			https: 443
		}
		, urlp = parseUrl(url)
		;

		return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : '');
	}