2013-04-16 112 views
3

我正在學習PHP中的套接字編程,所以我正在嘗試一個簡單的echo-chat服務器。

我寫了一個服務器,它的工作原理。我可以將兩個netcats連接到它,當我在一個netcat中寫入時,我會在另一個netcat上進行重新配置。現在,我想實現NC在PHP中所做的工作PHP:從套接字或STDIN中讀取

我想使用stream_select來查看我是否在STDIN上或套接字上有數據,以便將STDIN中的消息發送到服務器或從服務器讀取傳入消息。 不幸的是,在php手冊中的例子並沒有給我任何線索如何做到這一點。我嘗試了$ line = fgets(STDIN)和socket_write($ socket,$ line),但它不起作用。所以我開始走下坡路,只是想讓stream_select在用戶輸入消息時動作起來。

$read = array(STDIN); 
$write = NULL; 
$exept = NULL; 

while(1){ 

    if(stream_select($read, $write, $exept, 0) > 0) 
     echo 'read'; 
} 

給人

PHP的警告:stream_select():沒有流陣列中 /home/user/client.php獲得通過在線18

但是,當我的var_dump( $ read)它告訴我,它是一個有數據流的數組。

array(1) { 
    [0]=> 
    resource(1) of type (stream) 
} 

如何讓stream_select工作?


PS:在Python中我可以這樣做

r,w,e = select.select([sys.stdin, sock.fd], [],[]) 
for input in r: 
    if input == sys.stdin: 
     #having input on stdin, we can read it now 
    if input == sock.fd 
     #there is input on socket, lets read it 

我需要在PHP

+0

看來這個警告,當你設置tv_sec 1 –

+0

不,當我設置tv_sec爲1,它只是延緩了警告1秒不顯示... – fdafgfdgfagfdagfdagfdagfdagfda

回答

2

同我找到了解決辦法。它似乎工作,當我使用:

$stdin = fopen('php://stdin', 'r'); 
$read = array($sock, $stdin); 
$write = NULL; 
$exept = NULL; 

而不是隻是STDIN。儘管php.net說,STDIN已經打開並且使用 $ stdin = fopen('php:// stdin','r'); 似乎不是,如果你想將它傳遞給stream_select。 此外,服務器的套接字應使用$ sock = fsockopen($ host)創建;而不是在客戶端使用socket_create ...得愛這種語言,它的合理性和清晰的手冊...

這裏的一個客戶端的工作示例,連接到回聲服務器使用選擇。

<?php 
$ip  = '127.0.0.1'; 
$port = 1234; 

$sock = fsockopen($ip, $port, $errno) or die(
    "(EE) Couldn't connect to $ip:$port ".socket_strerror($errno)."\n"); 

if($sock) 
    $connected = TRUE; 

$stdin = fopen('php://stdin', 'r'); //open STDIN for reading 

while($connected){ //continuous loop monitoring the input streams 
    $read = array($sock, $stdin); 
    $write = NULL; 
    $exept = NULL; 

    if (stream_select($read, $write, $exept, 0) > 0){ 
    //something happened on our monitors. let's see what it is 
     foreach ($read as $input => $fd){ 
      if ($fd == $stdin){ //was it on STDIN? 
       $line = fgets($stdin); //then read the line and send it to socket 
       fwrite($sock, $line); 
      } else { //else was the socket itself, we got something from server 
       $line = fgets($sock); //lets read it 
       echo $line; 
      } 
     } 
    } 
}