2012-10-21 62 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