2012-10-21 136 views
8

用下面的代码,我可以收到1个请求,并把它写:PHP插座听力环

function listen() 
{ 
    // Set time limit to indefinite execution 
    set_time_limit (0); 

    // Set the ip and port we will listen on 
    $address = 'XX.XX.XX.XXX'; 
    $port = XXXX; 

    // Create a TCP Stream socket 
    $sock = socket_create(AF_INET, SOCK_STREAM, 0); 

    // Bind the socket to an address/port 
    $bind = socket_bind($sock, $address, $port); 

    // Start listening for connections 
    socket_listen($sock); 

    /* Accept incoming requests and handle them as child processes */ 
    $client = socket_accept($sock); 

    // Read the input from the client – 1024 bytes 
    $input = socket_read($client, 2024); 

    // Strip all white spaces from input 
    echo $input; 

    // Close the master sockets 
    $close = socket_close($sock); 

    var_dump($close); 
} 

listen(); 

但它自动关闭,一旦收到1包侦听。我需要继续接收数据包,直到收到退出或任何关闭命令。

我应该如何改变上面的代码使这个函数成为一个循环?

回答

7
set_time_limit (0); 

$address = '46.49.41.188'; 

$port = 7777; 
$con = 1; 
$word = ""; 

$sock = socket_create(AF_INET, SOCK_STREAM, 0); 
$bind = socket_bind($sock, $address, $port); 

socket_listen($sock); 

while ($con == 1) 
{ 
    $client = socket_accept($sock); 
    $input = socket_read($client, 2024); 

    if ($input == 'exit') 
    { 
     $close = socket_close($sock); 
     $con = 0; 
    } 

    if($con == 1) 
    { 
     $word .= $input; 
    } 
} 

echo $word; 

如果要求将退出听会关闭。该方法已经过测试:),它的工作原理。

+0

如果我通过这个端口发送数据,我得到一个字符,然后停止打印任何东西。我想这是原始海报的问题。 – adrianTNT

1

如何:

function listen(){ 
// Set the ip and port we will listen on 
$address = 'XX.XX.XX.XXX'; 
$port = XXXX; 
// Create a TCP Stream socket 
$sock = socket_create(AF_INET, SOCK_STREAM, 0); 
// Bind the socket to an address/port 
$bind = socket_bind($sock, $address, $port); 
// Start listening for connections 
socket_listen($sock); 
/* Accept incoming requests and handle them as child processes */ 
$client = socket_accept($sock); 
// Read the input from the client – 1024 bytes 
$input = socket_read($client, 2024); 
// Strip all white spaces from input 
echo $input; 
// Close the master sockets 
$close = socket_close($sock); 
var_dump($close); 
listen(); 
} 
set_time_limit (0); 
listen(); 
+0

首先感谢您的答案:)...我会尝试这个例子,但问题是:socket_close无法快速关闭套接字。我有一个例子如何让我的代码循环。我会写这个代码。 – Dest