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.
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.
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.
PHP serves requests synchronously. It means that each line of code executes in the synchronous manner of the script.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With