DEV Community

loading...
Cover image for PHP Non-blocking Socket: Part 1

PHP Non-blocking Socket: Part 1

aldora713 profile image ShakalakaB Updated on ・1 min read

In PHP Blocking Socket, I introduced the concept of blocking socket. Now, I would unpack 'unblocking socket'.

With unblocking socket, we don't need the 'wait' as in blocking sockets, also no need to wait for the completion of operation, and can connect the server with more than one client. Following is the example:

$address = '127.0.0.1';
$port = 10000;

ob_implicit_flush();

$sock = socket_create(AF_INET, SOCK_STREAM, 0);

socket_bind($sock, $address, $port) or die('Could not bind to address');

socket_listen($sock);

socket_set_nonblock($sock);

$clients = [];
$seconds = 0;

while (true) {
    if ($newsock = socket_accept($sock)) {
        echo "inside socket accept\n";
        if (is_resource($newsock)) {
            socket_set_nonblock($newsock);

            echo "New client connected\n";

            $clients[] = $newsock;
        }
    }

    if (count($clients)) {
        foreach ($clients AS $k => $v) {
            if ($input = socket_read($v, 1024)) {
                $input = trim($input);

                echo "$k: $input\n";

                $response = "Received" . "\n";
                socket_write($v, $response, strlen($response));

                if ($input == 'quit') {
                    socket_close($v);
                    unset($clients[$k]);
                }
            }
        }
    }

    sleep(1);
}

socket_close($sock);

I use socket_set_nonblock() to set socket to non-blocking mode. Now, the socket would return immediately even the connection or read has not completed. Thus, this enables us to perform multiple socket connections. But then comes another problem: how can I get the message from socket, so I use foreach to loop through sockets. If socket_read gets the message from clients, then server replies, if not, it enters another loop. The code for clients is same as the one in Part 1, try it yourself, and you can get a better understanding.

Discussion

pic
Editor guide
Collapse
pachijun profile image
pachijun

Thanks for the nice article.

Could you explain when socket_close($sock); is executed?
It seems that the script never breaks out of the while statement and never reaches the last line of code.

I'm new to TCP Socket world, so I would really appreciate it if you gave me a bit of explanation.

Collapse
aldora713 profile image
ShakalakaB Author

while(true) make sure the socket is always running until we interrupt, and once it is stopped, socket_close($sock) closes the socket resource, otherwise, the socket resource would be open

Collapse
jpolvora profile image
Jone Polvora

while (true) ...