2012-10-21 19 views
8

Con questo codice, posso ricevere 1 richiesta e scrivere:PHP presa ascolto anello

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(); 

Ma chiudere automaticamente ascolto volta ricevuto 1 pacchetto. Devo continuare a ricevere i pacchetti finché non viene ricevuta un'uscita o un comando di chiusura.

In che modo è necessario modificare il codice riportato sopra per rendere questa funzione un ciclo?

risposta

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; 

Se la richiesta sarà l'ascolto di uscita sarà chiusa. Quel metodo è stato testato :) e funziona.

+0

Se invio i dati attraverso questa porta, ottengo un carattere, quindi smette di stampare qualsiasi cosa. Immagino che questo fosse il problema del poster originale. – adrianTNT

1

ne dite:

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

innanzitutto grazie per la risposta:) ... proverò questo esempio ma il problema è che: socket_close non può chiudere il socket rapidamente. ho un esempio su come rendere il mio codice in loop. scriverò quel codice – Dest