Skip to content

Instantly share code, notes, and snippets.

@adamziel
Created March 13, 2024 11:08
Show Gist options
  • Save adamziel/c90dd65a3919465e6a03943de792dfe2 to your computer and use it in GitHub Desktop.
Save adamziel/c90dd65a3919465e6a03943de792dfe2 to your computer and use it in GitHub Desktop.
<?php
function download_url_stream_socket_client( $url ) {
$stream = stream_socket_client(
$url,
$errno,
$errstr,
30,
STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT
);
if ( $stream === false ) {
throw new Exception( 'Unable to open stream' );
}
return $stream;
}
echo 'Before download_url' . PHP_EOL;
// Measure time
$time_start = microtime( true );
$stream1 = download_url_stream_socket_client( 'tcp://downloads.wordpress.org:443' );
echo 'After the first download_url' . PHP_EOL;
$stream2 = download_url_stream_socket_client( 'tcp://downloads.wordpress.org:443' );
echo 'After the second download_url' . PHP_EOL;
// Measure time
$time_end = microtime( true );
$time = $time_end - $time_start;
echo "Download initiated in $time seconds\n";
stream_socket_enable_crypto( $stream1, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT );
stream_set_blocking( $stream1, 0 );
// Wait until $stream1 is ready for writing
$EOF = false;
do {
$tmp = null;
$read = [];
$write = [ $stream1 ];
$except = null;
$ready = stream_select( $read, $write, $except, 0, 50000 );
if ( $ready === false ) {
// something went wrong!!
break;
} elseif ( $ready > 0 ) {
var_dump( "Ready: $ready" );
echo fwrite( $stream1, "GET /\n" );
// echo stream_socket_sendto( $stream1, "GET /\n\n" );
break;
} else {
// No data in the current cycle
}
} while ( ! $EOF );
$EOF = false;
do {
$tmp = null;
$read = [ $stream1 ];
$write = [];
$except = null;
$ready = stream_select( $read, $write, $except, 0, 50000 );
if ( $ready === false ) {
// something went wrong!!
break;
} elseif ( $ready > 0 ) {
var_dump( "Ready: $ready" );
echo fread( $stream1, 819200 );
// echo stream_socket_recvfrom( $stream1, 819200 );
break;
} else {
// No data in the current cycle
}
} while ( ! $EOF );
//echo stream_socket_sendto( $fp1, "GET /\n" );
//echo stream_socket_recvfrom( $fp1, 8192 );
////fwrite( $fp1, "GET /\n" );
////echo fread( $fp1, 8192 );
////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment