找到当前未被占用的端口号

@param {Number} [port] 查找的起始端口号
@return {Promise}
540773
function findAvailablePort(port = 9528) {
    return new Promise((resolve, reject) => {
        const check = () => {
            portIsOccupied(port, (isFound) => {
                if (isFound) {
                    resolve(port);
                } else {
                    port++;

                    if (port > 65535) {
                        reject();
                    } else {
                        check();
                    }
                }
            });
        };

        check();
    });
}
1021557
def get_port(self, adapter_number, port_number):
        
        for port in self.ports:
            if port.adapter_number == adapter_number and port.port_number == port_number:
                return port
        return None
491116
function parseInteger (name, port) {
  const portNumber = Number(port)
  if (!portNumber) {
    console.error(`Provided ${name} must be an integer`)
    process.exit(1)
  }
  return portNumber
}
155307
public static WebsocketServerTransport create(int port) {
    HttpServer httpServer = HttpServer.create().port(port);
    return create(httpServer);
  }
625983
public Integer getPort(int defaultPort)
	{
		String port = getParameterValue(PORT);

		try
		{
			if (port != null)
			{
				return Integer.parseInt(port);
			}
		}
		catch (Exception ex)
		{

		}
		
		return defaultPort;
	}
176688
private function formatPort($port = null): ?int
    {
        if (null === $port || '' === $port) {
            return null;
        }

        if (!is_int($port) && !(is_string($port) && 1 === preg_match('/^\d*$/', $port))) {
            throw new SyntaxError(sprintf('The port `%s` is invalid', $port));
        }

        $port = (int) $port;
        if (0 > $port) {
            throw new SyntaxError(sprintf('The port `%s` is invalid', $port));
        }

        $defaultPort = self::SCHEME_DEFAULT_PORT[$this->scheme] ?? null;
        if ($defaultPort === $port) {
            return null;
        }

        return $port;
    }
1331962
public synchronized UndertowServerEngine retrieveHttpServerEngine(int port)
   {
      UndertowServerEngine engine = null;
      synchronized(portMap)
      {
         engine = portMap.get(port);
      }
      return engine;
   }
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;
	}
1318118
function () {
    "use strict";

    return new Promise(function (resolve, reject) {
      var numberOfRetries = 5;

      (function retry () {
        var port = 4000 + Math.floor(Math.random() * 1000);
        portscanner.checkPortStatus(port, 'localhost', function (err, status) {
          if (err || status !== 'closed') {
            if (--numberOfRetries > 0) {
              setTimeout(retry);
            } else {
              reject('Cannot find a free port... giving up');
            }
          } else {
            resolve(port);
          }
        });
      })();
    });
  }
851823
function FetchLongPollingTransport(fetch) {
  var _super = new LongPollingTransport()
  var that = Transport.derive(_super)

  /**
   * Implements transport via fetch() API
   * @param {Object} packet
   */
  that.xhrSend = function (packet) {
    fetch(packet.url, {
      method: 'post',
      body: packet.body,
      headers: Object.assign(packet.headers, {
        'Content-Type': 'application/json;charset=UTF-8'
      })
    })
    .then(function (response) {
      return response.json()
    })
    .then(packet.onSuccess)
    .catch(packet.onError)
  }

  return that
}
399255
def get_ports(ports):
    
    if '-' in ports:
        # example: '10-15' at this point
        start, stop = ports.split('-')
        # start, stop = '10', '15'
        # return range(10, 16) --> iter([10, 11, 12, 13, 14, 15])
        return range(int(start), int(stop) + 1)
    # Simply int each port that is split out:
    # '10,11,12' --> ['10', '11', '12'] --> iter([10, 11, 12])
    return (int(p) for p in ports.split(','))
997633
function _websocketPort(ctx, port) {
  const forwarded = ctx.header['x-forwarded-proto'];
  const protocol = forwarded ? forwarded.split(',')[0] : undefined;
  return protocol === 'https' ? 443 : port;
}
1167074
function isAvailable(port) {
    return new Promise((resolve, reject) => {
        const server = net.createServer();

        server.unref();
        server.on('error', reject);
        const options = {};
        options.port = port;
        server.listen(options, () => {
            const { port } = server.address();
            server.close(() => {
                resolve(port);
            });
        });
    });
}
283515
function(port) {
      var port = port || this.conf.port || 80;
      var server = this.app.listen(port, function() {
        console.log("WeChat server for %s starts...", self.url);
      });
      server.on('error', function(err) {
        console.log(err);
      });
    }
408127
def with_port(self, port):
        
        # N.B. doesn't cleanup query/fragment
        if port is not None and not isinstance(port, int):
            raise TypeError("port should be int or None, got {}".format(type(port)))
        if not self.is_absolute():
            raise ValueError("port replacement is not allowed " "for relative URLs")
        val = self._val
        return URL(
            self._val._replace(
                netloc=self._make_netloc(
                    val.username, val.password, val.hostname, port, encode=False
                )
            ),
            encoded=True,
        )
881632
function isPortInUse(port) {
  _validatePortFormat(port);
  if (isPlatform('unix')) {
    if (isPlatform('linux') && fileExists('/proc/net')) {
      return _isPortInUseRaw(port);
    } else if (isInPath('netstat')) {
      return _isPortInUseNetstat(port);
    } else {
      throw new Error('Cannot check port status');
    }
  } else {
    throw new Error('Port checking not supported on this platform');
  }
}
781510
function checkPort(port, host, callback) {
    var socket = new Socket(),
        status = null;
    socket.on('connect', () => {
        status = 'open';
        socket.end();
    });
    socket.setTimeout(1500);
    socket.on('timeout', () => {
        status = 'closed';
        socket.destroy();
    });
    socket.on('error', (exception) => {
        status = 'closed';
    });
    socket.on('close', (exception) => {
        callback(null, status,host,port);
    });
    socket.connect(port, host);
}