2010-07-23 7 views
0

PHP로 소켓 서버를 설정하려고합니다. 내가 socket_close ($ 산란을) 주석 후에도 ... 그것은 연결을받은 후 종료됩니다 php.net에서 촬영 한이 예를PHP 소켓 서버 연결이 끊어졌습니다

<? 
// 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

당신은 루프 또는 무언가에 동의 랩 할 필요가있다. 스크립트 실행이 끝났기 때문에 종료됩니다.

은 당신이 뭔가를 할 수 있습니다 : 그것은 무언가를 수신 할 때까지이 대기하도록 O_NONBLOCK 플래그없이

while ($spawn = socket_accept($socket)) { 

//do stuff 

} 
4

socket_read은 (socket_set_nonblock 참조), 차단 작업입니다.

무언가를 받자 마자 다음 스크립트를 수행 할 루프가 없으므로 나머지 스크립트가 계속 실행되고 종료됩니다. (예 : 서버에서 보통 while(true){} loop을 수행합니다.)

+0

감사합니다. 덕분에 – sonics876

+2

답변으로 표시합니다. :( – funwhilelost

관련 문제