PHP 8.3.4 Released!

stream_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_selectExecuta o equivalente à chamada de sistema select() nos arrays de fluxos informados com um limite de tempo especificado por segundos e microssegundos

Descrição

stream_select(
    ?array &$read,
    ?array &$write,
    ?array &$except,
    ?int $seconds,
    ?int $microseconds = null
): int|false

A função stream_select() aceita arrays de fluxos e espera por alteração em seus estados. Sua operação é equivalente à da função socket_select() exceto por atuar em fluxos.

Parâmetros

read

Os fluxos listados no array read serão observados para ver se caracteres se tornem disponíveis para leitura (mais precisamente, para ver se uma leitura não irá bloquear - em particular, um recurso de fluxo já se encontra pronto no final do arquivo, neste caso a função fread() irá retornar uma string com comprimento zero).

write

Os fluxos listados no array write serão observados para ver se uma escrita não irá bloquear.

except

Os fluxos listados no array except serão observados para chegada de dados excepcional ("fora-de-banda") de alta prioridade.

Nota:

Quando stream_select() retorna, os arrays read, write e except são modificados para indicar qual(is) recurso(s) de fluxo realmente tiveram o estado alterado. As chaves originais dos arrays são preservadas.

seconds

Os parâmetros seconds e microseconds formam juntos o parâmetro limite de tempo, seconds especifica o número de segundos e microseconds o número de microssegundos. O parâmetro timeout é um limite do tempo que stream_select() irá esperar antes de retornar. Se tanto seconds quanto microseconds forem iguais a 0, stream_select() não irá esperar por dados - em vez disso irá retornar imediatamente, indicando o estado atual dos fluxos.

Se seconds for null stream_select() pode bloquear indefinidamente, retornando somente quando um evento em algum dos fluxos observados ocorrer (ou se um sinal interromper a chamada de sistema).

Aviso

Usando um valor de 0 no limite de tempo permite que se faça pesquisa instantânea dos estados dos fluxos, entretanto, NÃO é recomendado usar um limite de 0 em um loop pois poderá causar um consumo excessivo de tempo de CPU.

É muito melhor especificar um limite de tempo de alguns segundos, embora caso seja necessário ficar verificando e executando outro código concorrentemente, usar um limite de pelo menos 200000 microssegundos ajudará a reduzir o consumo de CPU do seu script.

Lembre-se que o valor de limite de tempo é o tempo máximo que irá decorrer; stream_select() irá retornar tão logo os fluxos requisitados estiverem prontos para uso.

microseconds

Veja descrição de seconds.

Valor Retornado

Em caso de sucesso, stream_select() retorna o número de recursos de fluxo contidos nos arrays modificados, o que pode ser zero se o limite de tempo for alcançado antes que alguma coisa interessante aconteça. Em caso de erro, false é retornado e um aviso é emitido (isto pode acontecer se a chamada ao sistema for interrompida por algum sinal).

Registro de Alterações

Versão Descrição
8.1.0 microseconds agora pode ser nulo.

Exemplos

Exemplo #1 Exemplo de stream_select()

Este exemplo verifica se dados chegaram para leitura em $stream1 ou $stream2. Como o valor de limite de tempo é 0 a função retornará imediatamente:

<?php
/* Prepara o array de leitura */
$read = array($stream1, $stream2);
$write = NULL;
$except = NULL;
if (
false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
/* Lidando com erros */
} elseif ($num_changed_streams > 0) {
/* Pelo menos em um dos fluxos algo interessante ocorreu */
}
?>

Notas

Nota:

Devido a uma limitação no motor Zend atual, não é possível passar um modificador de constante como null diretamente como um parâmetro para uma função que espera que o parâmetro seja passado por referência. Em vez disso, use uma variável temporária ou uma expressão com o membro mais a esquerda sendo uma variável temporária:

<?php
$e
= NULL;
stream_select($r, $w, $e, 0);
?>

Nota:

Certifique-se de usar o operador === na verificação de erro. Como a função stream_select() pode retornar 0, a comparação com == pode ser interpretada como true:

<?php
$e
= NULL;
if (
false === stream_select($r, $w, $e, 0)) {
echo
"stream_select() falhou\n";
}
?>

Nota:

Se for realizada leitura/escrita em um fluxo retornado nos arrays, esteja ciente que não necessariamente serão lidos/escritos todos os dados solicitados. Esteja preparado para a possibilidade de se ler/escrever apenas um único byte.

Nota:

Alguns fluxos (como zlib) não podem ser selecionados por esta função.

Nota: Compatibilidade com Windows

O uso de stream_select() em descritores de arquivos retornados por proc_open() irão falhar e retornar false no Windows.

STDIN de um console muda de estado assim que qualquer evento de entrada estiver disponível, mas a leitura do fluxo ainda poderá bloquear.

Veja Também

add a note

User Contributed Notes 17 notes

up
4
php at richardneill dot org
14 years ago
Note that reading from a regular file which is on end-of-file will *not* block. You'll get a non-blocking, zero-byte read. However, stream_select *will* block if the input is a pipe, and there is no more data to be had.
up
5
Martin
5 years ago
Maintaining connection with multiple clients can be tricky, PHP script is single-thread process, so if you like to do more than one thing at once (like waiting for new connections and waiting for new data), you’ll have to use some sort of multiplexing.

<?php
$socket
= stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
stream_set_blocking($socket, 0);

$connections = [];
$read = [];
$write = null;
$except = null;

while (
1) {

// look for new connections
if ($c = @stream_socket_accept($socket, empty($connections) ? -1 : 0, $peer)) {
echo
$peer.' connected'.PHP_EOL;
fwrite($c, 'Hello '.$peer.PHP_EOL);
$connections[$peer] = $c;
}

// wait for any stream data
$read = $connections;
if (
stream_select($read, $write, $except, 5)) {

foreach (
$read as $c) {
$peer = stream_socket_get_name($c, true);

if (
feof($c)) {
echo
'Connection closed '.$peer.PHP_EOL;
fclose($c);
unset(
$connections[$peer]);
} else {
$contents = fread($c, 1024);
echo
$peer.': '.trim($contents).PHP_EOL;
}
}
}
}
?>
up
5
aidan at php dot net
19 years ago
If you want to set an absolute maximum execution time for stream_select in a loop, it's important to decrement the max_time value passed to stream_select.

<?php
// The maximum time for execution in milliseconds
$maxtime = 200000;
// The time the loop started
$starttime = microtime(true);
// Original array of sockets
$r = $orig_sockets;

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
return
$maxtime - ((microtime(true) - $starttime) * 1000000);
}

while (
stream_select($r, $w = null, $e = null, 0, calctimeout($maxtime, $starttime)) !== 0)
{
// loop through the sockets that showed activity
foreach ($r as $socket) {
// $socket talked
}

// stream_select modifies the contents of $r
// in a loop we should replace it with the original
$r = $orig_sockets;
}

?>
up
4
Sitsofe
5 years ago
When stream_select() fails you SHOULD NOT use the results of the arrays (i.e. read, write, except) that were passed into it as parameters. While doing so anyway won't trigger undefined behaviour, you are depending on unspecified behaviour that by definition is not guaranteed.

At the time of writing the PHP 7.2 interpreter does not modify the arrays upon stream_select() failure (see the code around https://github.com/php/php-src/blob/php-7.2.14/ext/standard/streamsfuncs.c#L842) thus a PHP program that doesn't heed the advice above can deceive itself as to the state of those streams.

(Hopefully this warning can be added to the main documentation one day)
up
4
asphp at dsgml dot com
8 years ago
Make sure not to pass the same variable in the 3 arguments to stream_select, or you'll only get the results from one of them and the others will be overwritten.
up
6
maartenwolzak at gmail dot com
17 years ago
Note that you should change the calctimeout function below to divide the outcome by 1.000.000 otherwise you'll be waiting for two years instead of one minute for the socket to timeout...

<?php

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
return (
$maxtime - ((microtime(true) - $starttime) * 1000000))/1000000;
}

?>
up
3
mark2xv at gmail dot com
10 years ago
If you're getting unexplainable problems with nonblocking sockets using stream_select, disable the buffers using:

stream_set_read_buffer($socket, 0);
stream_set_write_buffer($socket, 0);

For some reason when writing (in total) ~256k, sockets start returning FALSE when reading, yet always appear in the stream_select arrays. This fixed that problem. (for us.)
up
3
phpdoc at shemesh dot biz
19 years ago
Please note that, on return, the key of "read" will be zero based, serially numbered according to the streams for which there is read data ready only. In other words, if you want to know which of the original streams placed in "read" is ready, there is no immediate way of knowing that.

If you want to know which of the original stream is which, you can either use "==", or possibly set a reverse map array, in which the stream is the key, and the key to the original "read" array is the data.
up
2
rob at associatedtechs dot com
9 years ago
If you try to use stream_select() with fread(), you may get bit by a combination of bugs (https://bugs.php.net/bug.php?id=52602 and https://bugs.php.net/bug.php?id=51056). As of PHP 5.5.10, fread() and stream_select() don't reliably play well together.

If you need stream_select() and you don't need an encrypted connection (e.g. TLS), use stream_socket_recvfrom() instead of fread().

I can't find a way to reliably handle an encrypted connection with blocking functions in PHP; non-blocking might be the only way to do it.
up
2
Ben
17 years ago
You can key on file descriptors just fine by casting them to an int or a string, which returns what you would expect.
up
2
doingitwrong at mailismagic dot com
8 years ago
If you use stream_select() with a blocking stream, you are doing it wrong!

Just because this function returns something in one or more of the arrays does NOT mean that a future read or write operation will not block.

The above sentence is the most important sentence you will ever read regarding stream manipulation. Using stream_select() with blocking streams is a very common amateur mistake and causes major headaches when tracking down usage of this and similar select() system functions. PHP (and really the underlying OS) should verify that the supplied stream set is not blocking and throw an error/exception if any socket is set to block so that people are forced to fix their code. The documentation for stream_select() is, at best, misleading.

If you want a non-blocking stream, then set the stream to not block. Otherwise, live with the blocking stream. That is, after all, the whole point of blocking - to block indefinitely until the operation completes. select() is built for non-blocking streams ONLY. Any other use will result in very hard to track down bugs.

I got the above lecture many years ago after encountering the very bugs I mention. I fixed my code and now correct similar mistakes when I run into the issue elsewhere. Writing code for non-blocking streams is simpler than trying to write hacks for blocking streams with select() functions and ending up with application bugs.
up
1
aks at esoft dot dk
13 years ago
stream_select() looks deceptively like a simple wrapper around POSIX select(2).

But beware: while select(2) allows you to pass no file descriptors and use it as a "portable subsecond sleep", PHP will complain with "Warning: stream_select(): No stream arrays were passed in ****" if all arrays are empty or null, and it WONT sleep, it will return immediately. So... if the number of file descriptors you have isn't static, you have to deal with the special case yourself.
up
1
aidan at aidans dot org
17 years ago
Note that contrary to what the previous poster said, one is not able to use a stream resource as a key for an array. Rather, if you want to know which socket you are dealing with, consider using code similar to this:

<?php
$sockets
= array("sock_1" => $sock1, "sock_2" => $sock2, "sock_3" => $sock_3);

$read = $write = $error = $sockets;
$num = stream_select($read, $write, $error, 10);
if (
$n > 0) {
foreach (
$read as $r) {
$key = array_search($r, $sockets);
// $key will be "sock_1", "sock_2", "sock_3", etc.
}
}
?>

Hope that helps someone out there!
up
1
jerrywilborn at gmail dot com
14 years ago
http://bugs.php.net/bug.php?id=42682

This function will not return the number of changed streams under certain systems with older versions, but instead it will return '0'. Be careful.
up
0
bluej100@gmail
16 years ago
@mbaynton at gmail dot com

A handy syntactic trick:

<?php
$r
= Array($stream1, $stream2);
stream_select($r, $w = null, $x = null, 1337);
?>

I've seen it recommended elsewhere in the documentation for clarifying magic arguments so maintainers don't have to go check the function itself, but it also solves your problem here.
up
-1
Maxdamantus
16 years ago
Simple stream_select wrapper.. Returns the first stream in the array, and sets parameter 2 to the key (So that it is easy to identify what received data):

<?php
function select($array, &$vkey, $timeout=0){
$select = array();
$null = NULL;
foreach(
$array as $key => $sock){
$x = count($select);
$select[$x] = $sock;
$keys[$x] = $key;
}
if(
stream_select($select, $null, $null, $timeout)){
foreach(
$keys as $key){
if(
$array[$key] == $select[0]){
$vkey = $key;
return(
$select[0]);
}
}
}
}

$streams = array("foo" => $stream_one, "bar" => $stream_two); // Create an array of two (already existant) streams.
if($new = select($streams, $key, 60)){ //Sets $new to the resource that next gets new data, and $key to either "foo", or "bar", depending which one it is.
echo $key.":".stream_get_line($new, 2048)."\n";
}
?>
up
-2
lynch at php dot net
14 years ago
Note: At least one of the input arrays must be non-empty, or you get an E_WARNING message:
PHP Warning: stream_select(): unable to select [9]: Bad file descriptor (max_fd=0) in
To Top