Created
February 27, 2019 09:44
-
-
Save ramunasd/531214db3420ca8f95cb0fe0f3e5de21 to your computer and use it in GitHub Desktop.
Stream test
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 | |
error_reporting(-1); | |
ini_set('display_errors', 1); | |
$remote = isset($argv[1]) ? $argv[1] : 'tcp://google.com:80'; | |
$errorString = $errorCode = null; | |
$contextOptions = array(); | |
if (PHP_VERSION_ID >= 70100) { | |
$contextOptions['socket'] = array('tcp_nodelay' => true); | |
} | |
echo 'Connecting...', PHP_EOL; | |
$context = stream_context_create($contextOptions); | |
$stream = stream_socket_client( | |
$remote, | |
$errorCode, | |
$errorString, | |
1, | |
STREAM_CLIENT_CONNECT, | |
$context | |
); | |
if ($errorCode !== 0) { | |
die; | |
} | |
echo 'Setup stream...', PHP_EOL; | |
stream_set_timeout($stream, 1, 0) || trigger_error('Cannot set stream timeout'); | |
stream_set_blocking($stream, 0) || trigger_error('Cannot set stream non-blocking'); | |
stream_set_write_buffer($stream, 0) === 0 || trigger_error('Cannot set stream write buffer'); | |
stream_set_read_buffer($stream, 0) === 0 || trigger_error('Cannot set stream read buffer'); | |
$socket = socket_import_stream($stream); | |
socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1) || trigger_error('Cannot enable keepalive'); | |
echo 'Writing...', PHP_EOL; | |
$read = $except = null; | |
$write = array($stream); | |
$ready = stream_select($read, $write, $except, 1, 0); | |
if (!$ready) { | |
trigger_error('Stream is not ready for write'); | |
} else { | |
$size = 8192; | |
$data = str_repeat('0', $size); | |
for ($i = 0; $i < 100; $i++) { | |
$result = fwrite($stream, $data); | |
if ($result !== $size) { | |
trigger_error('Written less than buffer size: ' . $result); | |
} | |
} | |
} | |
fclose($stream); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment