Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-25.2.0 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Event::add(mixed $sock, callable $read_callback, callable $write_callback = null, int $flags = null)\:\ bool
fd, stream, sockets, stream_socket_client, fsockopen, object
Readable event callback function
Writeable event callback function
Flags:
OpenSwoole\Constant::EVENT_READ
OpenSwoole\Constant::EVENT_WRITE
OpenSwoole\Constant::EVENT_READ|OpenSwoole\Constant::EVENT_WRITE
If success, it returns TRUE, meaning the event listener was successfully added
Otherwise it returns FALSE, meaning there was an issue registering the event
Registers the read, write callback functions and flags of a socket on the Event Loop, creating a new event listener.
int: File descriptors, including OpenSwoole\Client->$sock, OpenSwoole\Process->$pipe or any other fdstream_socket_client/ fsockopen created PHP resourcesocket_create resource, but you must enable socket support at compile timeOpenSwoole\Process Or OpenSwoole\Client, these are automatically converted to a UnixSocket for a process and a client uses socket(OpenSwoole\Client)<?php
$fp = stream_socket_client("tcp://openswoole.com.com:80", $errno, $errstr, 30);
fwrite($fp,"GET / HTTP/1.1\r\nHost: openswoole.com\r\n\r\n");
OpenSwoole\Event::add($fp, function($fp) {
$resp = fread($fp, 8192);
// Remove the socket from event loop
OpenSwoole\Event::del($fp);
fclose($fp);
});
// Will not block the process, this line of code will be executed sequentially
echo "Finish\n";
Above, the readable event callback is using fread to read from the socket (you can also must recv), you must always use the proper read functions otherwise the event will continue to be triggered, you can then remove the event by using OpenSwoole\Event::del as shown in the example.
When using the Writeable event callback, you must write to the socket after the call to OpenSwoole\Event::del because the event needs to be removed before doing any other operations.
If you execute fread, socekt_recv, socket_read, OpenSwoole\Client::recv and they return false, with the error code EAGAIN. It means the current socket bugger does not have any data to read and you must wait for the event loop to read again.
And if you execute fwrite, socket_write, socket_send, OpenSwoole\Client::send and they return false, with the error code EAGAIN. It means the socket transmission buffer is full, you are then temporarily unable to send data and need to wait for a read event to take place on the event loop.
Manage fds with the EventLoop, for example monitoring file changes with inotify:
<?php
$fd = inotify_init();
OpenSwoole\Event::add($fd, function () use ($fd) {
$var = inotify_read($fd);
var_dump($var);
});