Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: socket_select - Manual
[go: Go Back, main page]

PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<socket_recvfromsocket_send" width="11" height="7"/>
view the version of this page
Last updated: Sun, 07 May 2006

socket_select

(PHP 4 >= 4.1.0, PHP 5)

socket_select --  与えられたソケットの配列に対し、指定した有効時間で select() システムコールを実行する

説明

int socket_select ( array &read, array &write, array &except, int tv_sec [, int tv_usec] )

socket_select() はソケットの配列を受け取り、 それらの状態が変化するまで待ちます。BSD のソケットについての 知識がある方なら、これらのソケットの配列が、いわゆるファイル記述子 セットであることがご理解いただけるでしょう。3 つの独立した 配列で、ソケットリソースが監視されます。

配列 read に挙げられたソケットでは、 文字が読み込み可能になっているかどうか(厳密に言うと、読み込みが ブロックされていないかどうか - 実際には、ソケット記述子はファイルの 終端でも有効です。そのような場合、socket_read() は長さゼロの文字列を返します)を監視します。

配列 write に挙げられたソケットでは、 書き込みがブロックされていないかどうかを監視します。

配列 except に挙げられたソケットでは、 例外を監視します。

警告

終了時に配列は書き換えられ、どのソケットの状態が変わったのかが わかるようになります。

socket_select() のすべての配列を設定する必要は ありません。使用しないものについては空の配列や NULL をかわりに 指定しておくことが可能です。また、これらの配列は参照渡し であり、socket_select() をコールした後でその中身が 書き換えられていることに注意しましょう。

例 1. socket_select() の例

<?php
/* 読み込み用の配列を準備する */
$read = array($socket1, $socket2);

$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0);

if (
$num_changed_sockets === false) {
  
/* エラー処理 */
} else if ($num_changed_sockets > 0) {
  
/* すくなくともひとつのソケットで、何らかの出来事が起こっています */
}
?>

注意: 現状の Zend Engine の制限により、関数の参照渡しパラメータに NULL のような定数値を直接渡すことができません。一時的な 変数を使用するか、あるいは一番左に一時変数を使用する式を 使用してください。

例 2. socket_select() での NULL の使用

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

tv_sec および tv_usec は、ともにタイムアウトを指定するパラメータです。 タイムアウトは、socket_select() が結果を返すまでの経過時間の最大値です。 tv_sec はゼロにすることも可能で、そうすると socket_select() は結果をすぐに返します。 これはポーリングをする際に有用です。tv_secNULL(タイムアウトしない)を指定すると、 socket_select() は無期限にブロックします。

成功した場合は、socket_select() は配列内で 変化のあったソケットリソースの数を返します。もし何かがおこる前に タイムアウト時間が経過した場合は、ゼロを返すことになります。 エラー時には FALSE が返されます。エラーコードは socket_last_error() で取得可能です。

注意: エラーかどうかを調べる際には、必ず === 演算子を 使用するようにしましょう。socket_select() は 0 を返す場合もあり、このような場合に == を用いて比較すると、エラーと判定されてしまいます。

例 3. socket_select() の返す結果を知る

<?php
if (false === socket_select($r, $w, $e = NULL, 0)) {
   echo
"socket_select() は失敗しました。原因: " .
      
socket_strerror(socket_last_error()) . "\n";
}
?>

注意: ソケットの実装によっては、取り扱いに注意すべきものがあることを 知っておいてください。基本的なルールは以下のとおりです。

  • 基本的に socket_select() のタイムアウトは 指定しないように心がけましょう。もしデータがなかった場合に、 プログラム側でそれを判定できなくなってしまいます。タイムアウトに 依存しているコードは移植性が悪く、デバッグが困難です。

  • socket_select() のコール後に値をチェックして 適切に処理するつもりがないソケットリソースは、決して配列に追加 してはいけません。 socket_select() から値が返ってきたあとは、配列内の すべてのソケットリソースをチェックする必要があります。すべての書き込み用 ソケットは書き込める必要がありますし、またすべての読み込み用ソケットは 読み込める必要があります。

  • 配列で返されたソケットに対して読み込み/書き込みをする場合には、 指定したデータを必ずしもすべて読み込み/書き込みするとは限らないことを 知っておいてください。たった 1 バイトしか読み込み/書き込みが できなかった場合にも対処できるよう準備しておきましょう。

  • ほとんどのソケット実装で、except でキャッチできる 例外はただひとつ、すなわちソケットが受け取ったデータが帯域外で あったということだけです。

socket_read()socket_write()socket_last_error() および socket_strerror() も参照ください。



add a note add a note User Contributed Notes
socket_select
Whosawhatsis at that google email thingy
20-Apr-2006 11:35
Another solution to the problem of keys not being preserved is to have an additional array for looking up sockets that uses their resource identifiers as keys. This can be obtained using array_flip() in some cases, but is particularly useful if each socket is associated with an object. In this case, you can make the object's constructor add a pointer to itself to the lookup array with its socket resource identifier as a key and use the following code to execute a read method for the object associated with each socket returned by socket_select():

<?php
socket_select
($reads, $writes, $excepts, 0);

foreach (
$sockets as $socket) {
  
$lookuparray[$socket]->read();
}
?>
ludvig dot ericson at gmail dot com
02-Nov-2005 10:35
Regarding the comment below, No, it does not, it's a system call and I believe it's rather hard to preserve keys.

Additionally, socket_select should be used like it was a user-inputted array, that you don't know what you sent in to.

<?php
$reads
= $clients;
$reads[] = $server;

socket_select($reads);

foreach (
$reads as $read) {
  
/* do some stuff */
}
?>
crimson at NOSPAMtechnologist dot com
01-Oct-2005 08:15
Note that the resulting arrays do NOT maintain keys (PHP 4.3.2) after being run through this function:

Before:
Array
(
   [Client_Socket] => Resource id #6
   [Server_Socket] => Resource id #9
)

After:
Array
(
   [0] => Resource id #6
   [1] => Resource id #9
)

It would have been nice to have the keys stay to figure out which stream you need to receive from, but you'll have to use some fancy foreach loop to figure out which sockets to check.
vardhan ( at ) rogers ( dot ) com
28-Aug-2005 11:46
A simple PHP script using socket_select() to manage multiple connections.
connect using "telnet localhost 9050". it broadcasts your messages that you send through telnet to other users connected to the server -- sort of like a chat script

#!/usr/local/bin/php
<?php

   $port
= 9050;
  
  
// create a streaming socket, of type TCP/IP
  
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  
  
// set the option to reuse the port
  
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
  
  
// "bind" the socket to the address to "localhost", on port $port
   // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
  
socket_bind($sock, 0, $port);
  
  
// start listen for connections
  
socket_listen($sock);

  
// create a list of all the clients that will be connected to us..
   // add the listening socket to this list
  
$clients = array($sock);
  
   while (
true) {
      
// create a copy, so $clients doesn't get modified by socket_select()
      
$read = $clients;
      
      
// get a list of all the clients that have data to be read from
       // if there are no clients with data, go to next iteration
      
if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
           continue;
      
      
// check if there is a client trying to connect
      
if (in_array($sock, $read)) {
          
// accept the client, and add him to the $clients array
          
$clients[] = $newsock = socket_accept($sock);
          
          
// send the client a welcome message
          
socket_write($newsock, "no noobs, but ill make an exception :)\n".
          
"There are ".(count($clients) - 1)." client(s) connected to the server\n");
          
          
socket_getpeername($newsock, $ip);
           echo
"New client connected: {$ip}\n";
          
          
// remove the listening socket from the clients-with-data array
          
$key = array_search($sock, $read);
           unset(
$read[$key]);
       }
      
      
// loop through all the clients that have data to read from
      
foreach ($read as $read_sock) {
          
// read until newline or 1024 bytes
           // socket_read while show errors when the client is disconnected, so silence the error messages
          
$data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);
          
          
// check if the client is disconnected
          
if ($data === false) {
              
// remove client for $clients array
              
$key = array_search($read_sock, $clients);
               unset(
$clients[$key]);
               echo
"client disconnected.\n";
              
// continue to the next client to read from, if any
              
continue;
           }
          
          
// trim off the trailing/beginning white spaces
          
$data = trim($data);
          
          
// check if there is any data after trimming off the spaces
          
if (!empty($data)) {
          
              
// send this to all the clients in the $clients array (except the first one, which is a listening socket)
              
foreach ($clients as $send_sock) {
              
                  
// if its the listening sock or the client that we got the message from, go to the next one in the list
                  
if ($send_sock == $sock || $send_sock == $read_sock)
                       continue;
                  
                  
// write the message to the client -- add a newline character to the end of the message
                  
socket_write($send_sock, $data."\n");
                  
               }
// end of broadcast foreach
              
          
}
          
       }
// end of reading foreach
  
}

  
// close the listening socket
  
socket_close($sock);
?>
drenintell
02-May-2005 05:13
The continuation of my my previous post on 28-Apr-2005 10:19 at
http://ca3.php.net/manual/en/function.socket-select.php

Here it is: (Link is broken into 2 parts)

'http://gtkphp.org/php_socket_select_hangs
_explanation_and_solution.html'
Richard Neill
17-Sep-2004 01:37
It is probably a bad idea to watch an array of sockets for input with socket_select, and then socket_read() using PHP_NORMAL_READ.

Although this seems desirable, you can end up with a permanently blocked program, if someone sends you malformed input which is missing a trailing \n \r. Guess how I found that out.
calimero dot NOSPAM at NOSPAM dot creatixnet dot com
14-Feb-2003 09:36
Please note that the timeout parameter has important side-effects on the CPU usage of your script.

Setting the timeout to 0 will make your CPU looping without any time to have some rest and handle other running processes on your system, causing the system load to increase heavily while your script is running.

Personnaly, I use a value of 15 ms for this parameter. this ensures a good listening frequency while letting your system load clear.

Example :
$read = array($ListeningSocket);
$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0, 10);

Hope this helps.
daveb at optusnet dot com dot au
10-Sep-2002 01:27
If you haven't done any network programming before, PHP's socket_select() might appear a bit strange to you. I've written a simple php "partyline" script to demonstrate the multi-socket use of select'ing at http://dave.dapond.com/socketselect.php.txt
julian dot haupt at gmx dot de
10-Jul-2002 02:15
hello,
i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy

your script should look something like that:

<?php
$server
= new Server;
$client = new Client;

for (;;) {
  foreach (
$select->can_read(0) as $socket) {

   if (
$socket == $client->socket) {
    
// New Client Socket
    
$select->add(socket_accept($client->socket));
   }
   else {
    
//there's something to read on $socket
  
}
  }
}
?>

you should of course implement some routines to detect broken sockets and remove them from the select object.

you can also do output buffering and check in the main-loop for sockets that are ready to write

<?php
class select {
  var
$sockets;

  function
select($sockets) {

  
$this->sockets = array();

   foreach (
$sockets as $socket) {
    
$this->add($socket);
   }
  }

  function
add($add_socket) {
  
array_push($this->sockets,$add_socket);
  }

  function
remove($remove_socket) {
  
$sockets = array();

   foreach (
$this->sockets as $socket) {
     if(
$remove_socket != $socket)
      
$sockets[] = $socket;
   }

  
$this->sockets = $sockets;
  }

  function
can_read($timeout) {
  
$read = $this->sockets;
  
socket_select($read,$write = NULL,$except = NULL,$timeout);
   return
$read;
  }

  function
can_write($timeout) {
  
$write = $this->sockets;
  
socket_select($read = NULL,$write,$except = NULL,$timeout);
   return
$write;
  }
}
?>

<socket_recvfromsocket_send" width="11" height="7"/>
 Last updated: Sun, 07 May 2006
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2006 The PHP Group
All rights reserved.
This mirror generously provided by: PacketBusiness, Inc.
Last updated: Sun Sep 3 15:22:48 2006 JST