PHP.mk документација

stream_select

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.stream-select.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.stream-select.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
stream_select

Референца за `function.stream-select.php` со подобрена типографија и навигација.

function.stream-select.php

stream_select

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

stream_selectЈа извршува еквивалентната select() системска повика на дадените низи од стримови со тајм-аут одреден во секунди и микросекунди

= NULL

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

На stream_select() функцијата прифаќа низи од стримови и чека да им се промени статусот. Нејзината операција е еквивалентна на онаа на socket_select() функцијата, освен што делува на стримови.

Параметри

read

Стримовите наведени во read низата ќе се следат за да се види дали ќе станат достапни знаци за читање (поточно, дали читањето нема да блокира - особено, ресурс од стрим е подготвен и на крај од датотеката, во кој случај fread() ќе врати стринг со нулта должина).

write

Стримовите наведени во write низата ќе се следи за да се види дали пишувањето нема да блокира.

except

Стримовите наведени во except низата ќе се следи за пристигнување на високоприоритетни исклучоци („out-of-band“) податоци.

Забелешка:

Кога stream_select() враќа, низите read, write and except се менуваат за да покажат кој(и) ресурс(и) од стримот навистина го променил статусот. Оригиналните клучеви на arrayсе зачувуваат.

seconds

На seconds and microseconds заедно ја формираат timeout параметарот, seconds го специфицира бројот на секунди додека microseconds бројот на микросекунди. timeout е горна граница на времето што stream_select() ќе чека пред да врати. Ако seconds е поставен на 0 and microseconds is 0 or null, stream_select() нема да чека податоци - наместо тоа, веднаш ќе врати, покажувајќи го тековниот статус на стримовите.

Враќа seconds is null stream_select() може да блокира неодредено, враќајќи се само кога ќе се случи настан на еден од следените стримови (или ако сигнал го прекине системскиот повик).

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Користење на вредност на тајм-аут од 0 ви овозможува моментално да го проверите статусот на потоците, сепак, НЕ е добра идеја да користите 0 вредност за тајмаут во циклус бидејќи тоа ќе предизвика вашата скрипта да троши премногу време на процесорот.

Многу е подобро да се специфицира вредност за тајмаут од неколку секунди, иако ако треба да проверувате и извршувате друг код истовремено, користењето на вредност за тајмаут од најмалку 200000 микросекунди ќе помогне да се намали употребата на процесорот на вашата скрипта.

Запомнете дека вредноста за тајмаут е максималното време што ќе помине; stream_select() ќе се врати веднаш штом бараните потоци се подготвени за употреба.

microseconds

Константи за известување за грешки seconds description.

Вратени вредности

На успех stream_select() враќа број на ресурси на потокот содржани во изменетите низи, што може да биде нула ако тајмаутот истече пред да се случи нешто интересно. На грешка false се враќа и се крева предупредување (ова може да се случи ако системскиот повик е прекинат од дојден сигнал).

Дневник на промени

Верзија = NULL
8.1.0 microseconds сега е null.

Примери

Пример #1 stream_select() Пример

Овој пример проверува дали податоци пристигнале за читање на било кој од $stream1 or $stream2. Бидејќи вредноста за тајмаут е 0 ќе се врати веднаш:

<?php
/* Prepare the read array */
$read = array($stream1, $stream2);
$write = NULL;
$except = NULL;
if (
false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
/* Error handling */
} elseif ($num_changed_streams > 0) {
/* At least on one of the streams something interesting happened */
}
?>

Белешки

Забелешка:

Поради ограничување во тековниот Zend Engine не е можно да се помине константен модификатор како null директно како параметар на функција која очекува овој параметар да биде поминат со референца. Наместо тоа користете привремена променлива или израз со најлевиот член кој е привремена променлива:

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

Забелешка:

Бидете сигурни да го користите === операторот при проверка за грешка. Бидејќи stream_select() може да врати 0 споредбата со == би се проценила како true:

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

Забелешка:

Ако читате/пишувате на поток вратен во низите, бидете свесни дека тие не нужно читаат/пишуваат целосна количина на податоци што сте ја побарале. Бидете подготвени дури и само да прочитате/напишете еден бајт.

Забелешка:

Некои потоци (како zlibне може да биде избрано од оваа функција.

Забелешка: Компатибилност со Windows

Употреба на stream_select() на дескриптори на датотеки вратени од proc_open() ќе откаже и ќе врати false под Windows.

STDIN од конзола го менува статусот веднаш штом any се достапни настани за внесување, но читањето од потокот можеби сè уште блокира.

Види Исто така

  • stream_set_blocking() - Отворете постојана интернет или Unix доменска врска со сокет

Белешки од корисници за да означиме кој било валиден PHP израз.

php на richardneill точка org
пред 16 години
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.
Ситсофе
пред 7 години
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)
- Декодира стринг кодиран со URL
пред 7 години
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;
            }
        }
    }
}
?>
aidan на php точка net
21 години пред
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;
}

?>
мартенволзак на gmail точка com
19 години пред
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;
}

?>
аспхп на dsgml точка com
пред 10 години
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.
марк2хв на gmail точка com
12 години пред
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.)
пхпдок на shemesh точка biz
21 години пред
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.
роб на associatedtechs точка com
пред 11 години
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.
Бен
19 години пред
You can key on file descriptors just fine by casting them to an int or a string, which returns what you would expect.
акс на esoft точка dk
пред 15 години
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.
дуингетвронг на mailismagic точка com
пред 10 години
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.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.