views:

33

answers:

2

I'm trying to set up a socket server in php that stays open. This example taken from php.net will close after it receives connection...even after I comment out socket_close($spawn)

<?
// 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;
?>
A: 

You need to wrap the accept in a loop or something. It closes because the script execution has ended.

You could do something like this:

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

//do stuff

}
Joshua Smith
+1  A: 

socket_read without the O_NONBLOCK flag (see socket_set_nonblock) is a blocking operation, so it will wait there until it receives something.

As soon as something is received, the rest of the script continues, and exits, as there is no loop in place to do the next read. (i.e: in a server it's usual to do a while(true){} loop)

Wrikken
thanks it worked
Then mark it as the answer. :(
infamouse