Last active
April 20, 2020 10:17
-
-
Save joec4i/ef1b1156ed79e23487400c68a5f693cb to your computer and use it in GitHub Desktop.
A script to test stream_socket_client()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Usage: php socket_test.php [number_of_connections] [timeout] | |
ini_set('display_errors', 'On'); | |
ini_set('error_reporting', 'E_ALL'); | |
$n = (int)($argv[1] ?? 100); | |
$timeout = (float)($argv[2] ?? 0.5); | |
(new StreamSocketTest())->run($n, $timeout); | |
class StreamSocketTest | |
{ | |
/** @var int */ | |
private $errorCount = 0; | |
public function run(int $n, float $timeout): void | |
{ | |
$this->errorCount = 0; | |
$time = microtime(true); | |
for ($i = 0; $i < $n; $i ++) { | |
$this->runOnce($timeout); | |
sleep(0.3); | |
} | |
$elapsedTime = microtime(true) - $time; | |
echo "Tested {$n} connections(timeout={$timeout}) in {$elapsedTime}s with {$this->errorCount} errors\n"; | |
} | |
private function runOnce(float $timeout): void | |
{ | |
$time = microtime(true); | |
$socket = stream_socket_client("tlsv1.2://www.google.com:443", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT); | |
$elaspedTime = microtime(true) - $time; | |
if (is_resource($socket)) { | |
echo "connected in {$elaspedTime}s\n"; | |
fclose($socket); | |
} else { | |
$this->errorCount ++; | |
echo "failed in {$elaspedTime}s, error.no={$errno}, errstr={$errstr}\n"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment