2010-07-23 91 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