Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP asynchronously use sockets?

Tags:

Typical PHP socket functionality is synchronous, and halts the thread when waiting for incoming connections and data. (eg. socket_read and socket_listen)

How do I do the same asynchronously? so I can respond to data in a data received event, instead of polling for data, etc.

like image 247
Robin Rodricks Avatar asked Sep 16 '09 11:09

Robin Rodricks


People also ask

Are sockets asynchronous?

Asynchronous sockets use multiple threads from the system thread pool to process network connections. One thread is responsible for initiating the sending or receiving of data; other threads complete the connection to the network device and send or receive the data.

Can we use socket in PHP?

Socket programming can be defined as the programming approach that has the server and the client as the application where a connection has to be established between both of them to facilitate the communication between them. In terms of PHP, it also lets us implement the concept of socket programming.

Is PHP asynchronous or synchronous?

PHP serves requests synchronously. It means that each line of code executes in the synchronous manner of the script.

What is the difference between synchronous sockets and asynchronous sockets?

As I understand synchronous mode, the client blocks for a while until it receives the packet/ data message from the server. And in async mode, the client carries out another operation without blocking the current operation.


1 Answers

Yup, that's what socket_set_nonblock() is for. Your socket interaction code will need to be written differently, taking into account the special meanings that error codes 11, EWOULDBLOCK, and 115, EINPROGRESS, assume.

Here's some somewhat-fictionalized sample code from a PHP sync socket polling loop, as requested:

$buf = '';
$done = false;
do {
    $chunk = socket_read($sock, 4096);
    if($chunk === false) {
        $error = socket_last_error($sock);
        if($error != 11 && $error != 115) {
            my_error_handler(socket_strerror($error), $error);
            $done = true;
        }
        break;
    } elseif($chunk == '') {
        $done = true;
        break;
    } else { 
        $buf .= $chunk;
    }
} while(true);
like image 76
chaos Avatar answered Sep 19 '22 14:09

chaos