Page 1 of 1

Problem using socket_write() function

Posted: Thu Jan 26, 2012 11:57 am
by lemmer
Hi to all!
I have a CLI-based script which is acting as a simple socket server. It should listen to incoming messages and reply "yes" if incoming message is "say yes", otherwise "no".
The following code can read incoming messages, but when trying to write to socket I get "Broken pipe" error. Please advise, what could be the reason?

Code: Select all

<?php

set_time_limit(0);

if (!($socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
    die('Error creating new socket.');
}

if (!socket_bind($socket, '10.87.0.62', 10009)) {
    die('Error binding socket to TCP port.');
}

if (!socket_listen($socket)) {
    die('Error listening socket connections.');
}

while (true) {

    if (!($client = socket_accept($socket))) {
        die('Error creating communication socket.');
    }

    $input = '';
    while ($inp = socket_read($client, 1024)) {
        $input .= $inp;
    }
    $input = trim($input);

    if ($input == 'KILL') {
        socket_close($client);
        break;
    }

    $reply = ($input == 'say yes' ? 'yes' : 'no');
    socket_write($client, $reply);

    socket_close($client);
}

socket_close($socket);

?>

Re: Problem using socket_write() function

Posted: Fri Jan 27, 2012 1:18 pm
by tr0gd0rr
I think the socket handle may be garbage collected after a while. Try putting the socket_create(), socket_bind(), and socket_listen() functions inside the while loop but only run them when $socket is falsy.