На странице произошла ошибка #S51. Свяжитесь с вебмастером.На странице произошла ошибка #S51. Свяжитесь с вебмастером. PHP 5.6 и PHP 7 на русском: Функция stream_select() - Запускает эквивалент системного вызова select() на заданных массивах потоков с таймаутом, указанным параметрами tv_sec и tv_usec

stream_select

(PHP 4 >= 4.3.0, PHP 5)

stream_selectЗапускает эквивалент системного вызова select() на заданных массивах потоков с таймаутом, указанным параметрами tv_sec и tv_usec

Описание

int stream_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )

Функция stream_select() получает массивы потоков и ждёт изменения их статуса. Её работа эквивалентна работе функции socket_select(), за исключением того, что она работает с потоками.

Список параметров

read

Потоки, перечисленные в массиве read будут отслеживаться на предмет появления символов, доступных для чтения (точнее отслеживается, что чтение не будет блокироваться - в частности, потоковый ресурс также готов для чтения в конце файла, но в этом случае функция fread() будет возвращать строку нулевой длины).

write

Потоки, перечисленные в массиве write, будут отслеживаться на предмет того, что запись в них не будет блокироваться.

except

Потоки, перечисленные в массиве except, будут отслеживаться на предмет поступления высокоприоритетных исключительных (внеполосных или "out-of-band") данных.

Замечание:

Когда stream_select() возвращается, массивы read, write и except изменяются для того, чтобы указать, какие потоковые ресурсы на самом деле изменили статус.

Вам нет необходимости передавать каждый массив функции stream_select(). Вы можете использовать вместо этого пустые массивы или NULL. Также не забывайте, что эти массивы передаются по ссылке и будут изменены после выполнения функцииstream_select().
tv_sec

Параметры tv_sec и tv_usec вместе формируют параметр timeout, tv_sec указывает число секунд, а tv_usec - число микросекунд. Параметр timeout - это верхняя граница времени, которое функция stream_select() будет ожидать до возвращения. Если параметры tv_sec и tv_usec оба установлены в 0, то функция stream_select() не будет ожидать данных - вместо этого она вернётся немедленно, указывая текущий статус потоков.

Если параметр tv_sec равен NULL, то функция stream_select() может выполняться неопределённое время, возвращаясь только тогда, когда происходит событие на одном из отслеживаемых потоков (или если системный вызов прерывается сигналом).

Внимание

Использование значения тайм-аута 0 позволяет вам мгновенно опросить статус потоков, однако ПЛОХАЯ идея использовать значение тайм-аута 0 в цикле, так как это заставит ваш скрипт потреблять слишком много процессорного времени.

Гораздо лучше указать значение тайм-аута в несколько секунд, хотя если вам нужно проверять и одновременно запускать другой код, использование тайм-аута как минимум 200000 микросекунд поможет уменьшить использование процессорного времени вашим скриптом.

Запомните, что значение тайм-аута - это максимальное время, которое будет затрачено. Функция stream_select() вернётся как только запрошенные потоки будут готовы к использованию.

tv_usec

Смотрите описание параметра tv_sec.

Возвращаемые значения

В случае успеха функция stream_select() возвращает количество потоковых ресурсов, содержащееся в изменённых массивах, которое может равно нулю, если истёк тайм-аут до того, как произошло что-то интересное. В случае ошибки возвращается FALSE и возникает предупреждение (это может случится, если системный вызов прерывается входящим сигналом).

Примеры

Пример #1 Пример использованияstream_select()

Этот пример проверяет, что получены данные для чтения на потоках $stream1 или $stream2. Так как значение тайм-аута равно 0, функция возвратится немедленно:

<?php
/* Подготовить массив для чтения */
$read   = array($stream1$stream2);
$write  NULL;
$except NULL;
if (
false === ($num_changed_streams stream_select($read$write$except0))) {
    
/* Обработка ошибок */
} elseif ($num_changed_streams 0) {
    
/* Как минимум на одном из потоков произошло что-то интересное */
}
?>

Примечания

Замечание:

По причине ограничения в текущем Zend Engine невозможно передать постоянную NULL непосредственно как параметр в функцию, которая ожидает, что этот параметр будет передан по ссылке. Вместо этого используйте временную переменную или выражение, в котором крайний левый член будет временной переменной:

<?php
$e 
NULL;
stream_select($r$w$e0);
?>

Замечание:

Убедитесь, что используете оператор === при проверке на ошибку. Так как функция stream_select() может возвращать 0, сравнение с использованием == может возвращать TRUE:

<?php
$e 
NULL;
if (
false === stream_select($r$w$e0)) {
    echo 
"Произошла ошибка при вызове stream_select()\n";
}
?>

Замечание:

Если вы читаете/пишете в поток, возвращаемый в массивах, знайте, что они не обязательно читают/пишут полное количество данных, которое вы запросили. Будьте готовы к тому, чтобы иметь возможность читать/писать даже по одному байту.

Замечание:

Некоторые потоки (например, zlib) не могут быть выбраны этой функцией.

Замечание:

Совместимость с Windows: функция stream_select(), используемая на канале, возвращённом из функции proc_open(), может вызвать потерю данных под Windows 98.

Использование функции stream_select() на файловых дескрипторах, возвращённых функцией proc_open() не удастся и возвратит FALSE под Windows.

Смотрите также

  • stream_set_blocking() - Устанавливает блокирующий/неблокирующий режим на потоке

Коментарии

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 null0calctimeout($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;
}

?>
2004-06-22 14:30:23
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.
2005-03-14 03:33:10
http://php5.kiev.ua/manual/ru/function.stream-select.html
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$error10);
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!
2006-12-07 21:53:39
http://php5.kiev.ua/manual/ru/function.stream-select.html
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;
}

?>
2007-01-25 03:36:00
http://php5.kiev.ua/manual/ru/function.stream-select.html
Автор:
You can key on file descriptors just fine by casting them to an int or a string, which returns what you would expect.
2007-02-01 19:35:10
http://php5.kiev.ua/manual/ru/function.stream-select.html
Автор:
@mbaynton at gmail dot com

A handy syntactic trick:

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

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.
2007-08-21 19:31:09
http://php5.kiev.ua/manual/ru/function.stream-select.html
Автор:
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$key60)){ //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($new2048)."\n";
}
?>
2007-09-30 01:28:11
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.
2009-07-04 22:45:55
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.
2009-07-27 13:55:09
http://php5.kiev.ua/manual/ru/function.stream-select.html
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
2010-03-15 14:48:32
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.
2010-11-10 09:56:21
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.)
2013-08-20 19:52:21
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.
2014-07-18 15:26:19
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.
2015-06-18 01:35:33
http://php5.kiev.ua/manual/ru/function.stream-select.html
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.
2016-02-04 23:28:54
http://php5.kiev.ua/manual/ru/function.stream-select.html
Автор:
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$errstrSTREAM_SERVER_BIND STREAM_SERVER_LISTEN);
stream_set_blocking($socket0);

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

while (
1) {

   
// look for new connections
   
if ($c = @stream_socket_accept($socket, empty($connections) ? -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$except5)) {

        foreach (
$read as $c) {
           
$peer stream_socket_get_name($ctrue);

            if (
feof($c)) {
                echo 
'Connection closed '.$peer.PHP_EOL;
               
fclose($c);
                unset(
$connections[$peer]);
            } else {
               
$contents fread($c1024);
                echo 
$peer.': '.trim($contents).PHP_EOL;
            }
        }
    }
}
?>
2018-06-15 14:17:44
http://php5.kiev.ua/manual/ru/function.stream-select.html
Автор:
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)
2019-02-04 08:52:32
http://php5.kiev.ua/manual/ru/function.stream-select.html

    Поддержать сайт на родительском проекте КГБ