Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
<?php Swoole\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:
SWOOLE_EVENT_READ
SWOOLE_EVENT_WRITE
SWOOLE_EVENT_READ|SWOOLE_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 Swoole\Client->$sock
, Swoole\Process->$pipe
or any other fd
stream_socket_client
/ fsockopen
created PHP resourcesocket_create
resource, but you must enable socket support at compile timeSwoole\Process
Or Swoole\Client
, these are automatically converted to a UnixSocket for a process and a client uses socket(Swoole\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");
Swoole\Event::add($fp, function($fp) {
$resp = fread($fp, 8192);
// Remove the socket from event loop
Swoole\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 Swoole\Event::del
as shown in the example.
When using the Writeable event callback, you must write to the socket after the call to Swoole\Event::del
because the event needs to be removed before doing any other operations.
If you execute fread
, socekt_recv
, socket_read
, Swoole\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
, Swoole\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 fd
s with the EventLoop, for example monitoring file changes with inotify
:
<?php
$fd = inotify_init();
Swoole\Event::add($fd, function () use ($fd) {
$var = inotify_read($fd);
var_dump($var);
});