Skip to content

Instantly share code, notes, and snippets.

@joec4i

joec4i/socket_test.php

Last active Apr 20, 2020
Embed
What would you like to do?
A script to test stream_socket_client()
<?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