Skip to content

Instantly share code, notes, and snippets.

@CViniciusSDias
Created December 4, 2024 00:20
Show Gist options
  • Save CViniciusSDias/c812e8fea4299d4eb8483dd3c29d18b4 to your computer and use it in GitHub Desktop.
Save CViniciusSDias/c812e8fea4299d4eb8483dd3c29d18b4 to your computer and use it in GitHub Desktop.
I/O não bloqueante
<?php
$streams = [
stream_socket_client('tcp://example.org:80'),
fopen('composer.json', 'r'),
fopen('package.json', 'r'),
];
foreach ($streams as $stream) {
stream_set_blocking($stream, false);
}
fwrite($streams[0], "GET / HTTP/1.1\r\nHost: example.org\r\n\r\n");
$respostas = [];
$contentLength = [];
do {
$streamsParaLerNoLoop = $streams;
stream_select($streamsParaLerNoLoop, $write, $except, 1);
foreach ($streamsParaLerNoLoop as $indice => $stream) {
if (in_array($indice, [0], true)) { // se for HTTP
$conteudo = stream_get_contents($stream);
$fimHeaders = strpos($conteudo, "\r\n\r\n");
$headers = substr($conteudo, 0, $fimHeaders);
$corpo = $fimHeaders ? substr($conteudo, $fimHeaders + 4) : $conteudo;
if (!isset($respostas[$indice])) {
$respostas[$indice] = '';
}
$respostas[$indice] .= $corpo;
preg_match('/Content-Length: (\d+)/', $headers, $matches);
if (isset($matches[1])) {
$contentLength[$indice] = (int) $matches[1];
}
echo $respostas[$indice] . PHP_EOL;
if (strlen($respostas[$indice]) === $contentLength[$indice]) {
fclose($stream);
unset($streams[$indice]);
}
continue;
}
echo 'Arquivo: ' . strlen(stream_get_contents($stream)) . PHP_EOL;
if (feof($stream)) {
fclose($stream);
unset($streams[$indice]);
}
}
} while (!empty($streams));
<?php
$streams = [
stream_socket_client('tcp://example.org:80'),
fopen('composer.json', 'r'),
fopen('package.json', 'r'),
];
foreach ($streams as $stream) {
stream_set_blocking($stream, false);
}
fwrite($streams[0], "GET / HTTP/1.1\r\nHost: example.org\r\n\r\n");
do {
$streamsParaLer = $streams;
stream_select($streamsParaLer, $write, $except, 1);
foreach ($streamsParaLer as $indice => $stream) {
if ($indice > 0) { // arquivo
echo strlen(stream_get_contents($stream)) . PHP_EOL;
fclose($stream);
unset($streams[$indice]);
continue;
}
$conteudo = stream_get_contents($stream);
echo $conteudo . PHP_EOL;
echo strlen($conteudo);
fclose($stream);
unset($streams[$indice]);
}
} while(!empty($streams));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment