Problem using socket_write() function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lemmer
Forum Newbie
Posts: 1
Joined: Thu Jan 26, 2012 11:48 am

Problem using socket_write() function

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

?>
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Problem using socket_write() function

Post 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.
Post Reply