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.
stream_select
(PHP 4 >= 4.3.0, PHP 5)
stream_select — Belirtilen akım dizisi üzerinde belirtilen zaman aşımı ile select() sistem çağrısının eşdeğeri olarak çalışır
Açıklama
&$oku
, array &$yaz
, array &$dış
, int $saniye
[, int $mikrosaniye = 0
] )stream_select() işlevi akımları diziler halinde kabul eder ve durumları değişinceye kadar bekler. Akımlar üzerinde işlem yapması dışında socket_select() işlevinin benzeridir.
Değiştirgeler
-
oku -
okudizisindeki akımlar için veri okunabilir hale gelene kadar beklenir (daha doğrusu, okumanın engellenmediğini görene kadar - özellikle de akım özkaynağının dosya sonunda olduğu, fread() işlevinin sıfır uzunlukta bir dizge döndürdüğü duruma kadar). -
yaz -
yazdizisindeki akımlar için yazmanın engellenmediği görülene kadar beklenir. -
dış -
dışdizisindeki akımlar için yüksek öncelikli istisnai ("band dışı") veri gelinceye kadar beklenir.
stream_select() işlevine bu dizilerin hepsini aktarmak zorunda değilsiniz. Kullanmayacağınız dizileri ya boş bırakın ya da dizi yerineBilginize:
stream_select() dönerken
oku,yazvehariçdizilerinde akım özkaynaklarının değişen durumlarını belirten değişklikler yapılır.NULLbelirtin. Ayrıca, bu dizilerin gönderimli aktarıldıklarını ve stream_select() dönerken bunlarda değişiklik yapılacağını da unutmayın. -
saniye -
Son iki değiştirgenin toplamı stream_select() işlevinin dönmeden önce bekleyebileceği zaman aşımı süresini belirler. Bu değiştirgelerin ikisine de 0 belirtilirse stream_select() veri için beklemeden akımların durum bilgisiyle hemen dönecektir.
saniyedeğiştirgesindeNULLbelirtilirse stream_select(), izlediği akımlardan birinde bir olay vuku bulana kadar (veya sistem çağrısı bir sinyal ile durdurulana kadar), gerekirse sonsuza kadar engellenebilir.UyarıZaman aşımı olarak 0 belirtilmesi akımların anlık durumlarının dönmesini sağlar. Ancak, işlevi sıfır zaman aşımı ile bir döngüye sokmak çok fazla işlemci zamanı harcanacağından iyi bir fikir değildir.
Bir kaç saniyelik bir zaman aşımı belirtmek ve bu arada diğer denetimleri ve işlemleri yapmak daha iyidir. 200000 mikrosaniyelik bir zaman aşımı betiğinizin işlemci kullanımını düşürmenize yardımcı olacaktır.
Zaman aşımı değerinin beklenecek azami süreyi belirttiğini unutmayın. stream_select() işlevi istenen akımlar kullanıma hazır olunca, sürenin bitmesini beklemeden dönecektir.
-
mikrosaniye -
saniyedeğiştirgesinin açıklamasına bakınız.
Dönen Değerler
stream_select() işlevi başarı durumunda değişikliğe
uğrayan akımların sayısını döndürür. Hiçbir olay vuku bulmadan zaman aşımı
dolmuşsa işlev 0 döndürebilir. Bir hata durumunda işlev
FALSE döndürür ve bir uyarı çıktılanır (sistem çağrısı bir sinyal ile
kesilince de bu olur).
Örnekler
Örnek 1 - stream_select() örneği
Bu örnekte $oku1 ve $oku2
akımlarına okumak için bir veri gelmiş mi diye bakılmaktadır. Zaman aşımı
değeri 0 olduğundan işlev beklemeden dönmektedir.
<?php
/* Oku dizisini hazırlayalım */
$oku = array($oku1, $oku2);
$yaz = NULL;
$dış = NULL;
if (false === ($değişen_akım_sayısı = stream_select($oku, $yaz, $dış, 0))) {
/* Hata durumunda yapılacaklar */
} elseif ($değişen_akım_sayısı > 0) {
/* Akımların en azından birinde değişiklik olmuş */
}
?>
Notlar
Bilginize:
Zend motorunun sınırlamalarından dolayı, gönderimli aktarılan bir değiştirgeye doğrudan
NULLbelirtmek mümkün değildir. Bu nedenleNULLdeğerini doğrudan değil, bir değişken veya bir ifade üzerinden belirtin:<?php
$d = NULL;
stream_select($o, $y, $d, 0);
?>
Bilginize:
Hat durumlarını sınarken === işlecini kullanmanız gerektiğini unutmayın. Çünkü işlev 0 döndürdüğünde == işleci bunu
TRUEolarak değerlendirir. Örnek:<?php
$d = NULL;
if (false === stream_select($o, $y, $d, 0)) {
echo "stream_select() başarısız oldu\n";
}
?>
Bilginize:
Bir akıma okuma/yazma işlemi yapıyorsanız işlemek istediğiniz verinin tamamını işleme sokabileceğiniz gibi bir kanıya kapılmayın. Bazen ilk baytta işlem duruverir.
Bilginize:
Windows uyumluluğu: Windows 98 altında, proc_open() işlevinden dönen bir boru üzerinde stream_select() kullanımı veri kaybına sebep olabilir.
Windows altında, proc_open() işlevinden dönen dosya tanıtıcıları üzerinde stream_select() kullanımı başarısız olabilir ve
FALSEdönebilir.
Ayrıca Bakınız
- stream_set_blocking() - Akımın engelleme kipini ayarlar
You can key on file descriptors just fine by casting them to an int or a string, which returns what you would expect.
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!
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
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.
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.
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";
}
?>
@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.
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;
}
?>
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.
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;
}
?>
The documentation states that:
You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.
This appears to be incorrect, at least in PHP 5.1.6, because PHP sees these parameters are passed by reference and thus insists on a bona fide variable for the reference to refer to:
Fatal error: Only variables can be passed by reference
is what you get if you pass NULL or anything else literally.
