2010-07-23 125 views
0

我想在php中設置一個socket服務器,並保持打開狀態。從php.net採取接收連接後,將關閉......我註釋掉socket_close($產卵)即使在這個例子php socket服務器斷開

<? 
// set some variables 
$host = "192.168.1.109"; 
$port = 1234; 
// don't timeout! 
set_time_limit(0); 
// create socket 
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create 
socket\n"); 


// bind socket to port 
$result = socket_bind($socket, $host, $port) or die("Could not bind to 
socket\n"); 
// start listening for connections 
$result = socket_listen($socket, 3) or die("Could not set up socket 
listener\n"); 
// accept incoming connections 
// spawn another socket to handle communication 
$spawn = socket_accept($socket) or die("Could not accept incoming 
connection\n"); 
// read client input 
$input = socket_read($spawn, 1024) or die("Could not read input\n"); 
// clean up input string 
$input = trim($input); 
// reverse client input and send back 
//$output = $input . "\n"; 
$output = strrev($input) . "\n"; 
echo $input; 
socket_write($spawn, $output, strlen ($output)) or die("Could not write 
output\n"); 

// close sockets 
//socket_close($spawn); 
//socket_close($socket); 
?> 

and here is the code for the client connecting... 

<?php 
$fp = fsockopen("192.168.1.109", 1234, $errno, $errstr, 30); 
if (!$fp) { 
    echo "$errstr ($errno)<br />\n"; 
} else { 
    //$out = "testing"; 
    $out = "GET/HTTP/1.1\r\n"; 
    $out .= "Host: 127.0.0.1\r\n"; 
    $out .= "Connection: Close\r\n\r\n"; 
    $out .= "testing\n"; 
    fwrite($fp, $out); 
    while (!feof($fp)) { 
     echo fgets($fp, 128); 
    } 
    fclose($fp); 
    //exit(); 
} 
//exit; 
?> 

回答

0

您需要包裝在一個循環或東西的接受。它因爲腳本執行已結束而關閉。

你可以做這樣的事情:

while ($spawn = socket_accept($socket)) { 

//do stuff 

} 
4

socket_read沒有O_NONBLOCK標誌(見socket_set_nonblock)是一個阻塞操作,所以,直到它收到的東西它會在那裏等候。

只要收到一些東西,腳本的其餘部分就會繼續並退出,因爲沒有循環來執行下一次讀取。 (即:在服務器上通常做一個while(true){} loop

+0

感謝它的工作 – sonics876 2010-07-23 22:03:02

+2

然後將其標記爲答案。 :( – funwhilelost 2010-07-24 00:45:57