Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Event::write(mixed $fd, mixed $data)\:\ bool
fd
of the socket type
Data to send to the socket, must not exceed the length of the transmission data buffer size
If success, it returns TRUE, meaning the event listener was successfully added
Otherwise it returns FALSE, meaning there was an issue registering the event
Write data to the socket with async I/O, by using Event::write
you can achieve asynchronous data transmission, once the data buffer is full, a EAGAIN
error will be returned and the data waiting for a read event will be added to the transmission queue, once the socket is writeable again, OpenSwoole will automatically listen for the write event again.
When using Event:write
, if the operation is successful, the event loop automatically switches the socket to non-blocking mode. You also should not use Event::write
with SSL/TLS connections.
Under the hood, OpenSwoole will allow you to write as long as the buffer is not full, if it is full, OpenSwoole will write the extra data to memory and save it until a writeable event is triggered and the buffer becomes free again. If the memory buffer is also filled, OpenSwoole will then throw a pipe buffer overflow error and block the event loop waiting to write again.
<?php
$fp = stream_socket_client('tcp://127.0.0.1:9501');
$data = str_repeat('A', 1024 * 1024 * 2);
// Create the read callback
OpenSwoole\Event::add($fp, function($fp) {
echo fread($fp);
});
// Write data to the socket
OpenSwoole\Event::write($fp, $data);