Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use random available port rather than randomly generated one #36

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions src/ChromeDevtoolsProtocol/Instance/Launcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,11 @@ class Launcher
private $input;

/**
* @param int $port If port <= 0, random port number is generated.
* @throws \Exception
* @param int $port If port <= 0, random available port is used.
*/
public function __construct($port = 0)
{
if ($port <= 0) {
$port = random_int(1024 + 1, 65535);
}

$this->port = $port;
$this->port = max(0, $port);
}

/**
Expand Down Expand Up @@ -212,6 +207,10 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
$temporaryUserDataDir = null;
if (!$foundUserDataDir) {
$temporaryUserDataDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "chrome-profile-" . $this->port;
if ($this->port === 0) {
$temporaryUserDataDir .= "-" . bin2hex(random_bytes(8));
}

$fs->mkdir($temporaryUserDataDir);
$args[] = "--user-data-dir=" . $temporaryUserDataDir;
}
Expand All @@ -226,6 +225,16 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
);
$process->start();

if ($this->port === 0) {
$process->waitUntil(function ($type, $buffer) {
if (preg_match('~DevTools listening on ws://.+:(\d+)/devtools~', $buffer, $m)) {
$this->port = (int)$m[1];
return true;
}
return false;
});
}

$instance = new ProcessInstance($process, $temporaryUserDataDir, $this->port);

for (; ;) {
Expand Down