2014-02-24 32 views
0

我正在使用以下代码作为套接字服务器,而我试图学习套接字,但客户端代码将工作一次,我必须运行服务器脚本每次在我运行克林特代码之前。如何在第一次连接后打开php web套接字连接

等我什么时候运行这个server.php来继续监听客户端请求?

SERVER.PHP

$host = "127.0.0.1"; 
$port = 25003; 
set_time_limit(0); 
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); 
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); 
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); 
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); 
$input = socket_read($spawn, 1024) or die("Could not read input\n"); 
if ($input == "Hey"){ 
    $input = "Hey you don't shout me. Talk properly..."; 
    } else if ($input == "Vetra"){ 
     $input = "Hello how are you there, whats your name?"; 
     } else { $input = "Well, what can i say, you must be a human being."; 
} 
echo $input; 
$output = $input . "\n"; 
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n"); 
//socket_close($spawn); 
//socket_close($socket); 

CLIENT.PHP

$host = "127.0.0.1"; 
$port = 25003; 
$message = $_POST['data']; 
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); 
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n"); 
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n"); 
$result = socket_read ($socket, 1024) or die("Could not read server response\n"); 
echo $result; 
//socket_close($socket); 

回答

3

你应该等待在无限循环的新连接:

$host = "127.0.0.1"; 
$port = 25003; 
set_time_limit(0); 
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); 
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); 
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); 
while(true) { 
    $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); 
    $input = socket_read($spawn, 1024) or die("Could not read input\n"); 
    if ($input == "Hey"){ 
    $input = "Hey you don't shout me. Talk properly..."; 
    } else if ($input == "Vetra"){ 
    $input = "Hello how are you there, whats your name?"; 
    } else { 
    $input = "Well, what can i say, you must be a human being."; 
    } 
    echo $input.PHP_EOL; 
    $output = $input . "\n"; 
    socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n"); 
    socket_close($spawn); 
} 
+0

好适当的,而当做我跑了server.php?是不是会通过不断运行来利用资源? – user3109875

+0

没有。就像你在循环的最后一行看到的那样,你销毁了客户端套接字($ spawn),并且在第一行循环中等待新的分派。 – ziollek

+0

很好的答案,谢谢。 –