Swoole\Event->add

Declaration

<?php
Swoole\Event::add(mixed $sock, callable $read_callback, callable $write_callback = null, int $flags = null)\:\ bool

Parameters

sock

fd, stream, sockets, stream_socket_client, fsockopen, object

read_callback

Readable event callback function

write_callback

Writeable event callback function

flags

Flags: SWOOLE_EVENT_READ SWOOLE_EVENT_WRITE SWOOLE_EVENT_READ|SWOOLE_EVENT_WRITE

Return

success

If success, it returns TRUE, meaning the event listener was successfully added

false

Otherwise it returns FALSE, meaning there was an issue registering the event

Description

Registers the read, write callback functions and flags of a socket on the Event Loop, creating a new event listener.

Socket Types

  • int: File descriptors, including Swoole\Client->$sock, Swoole\Process->$pipe or any other fd
  • Stream Resource: A stream_socket_client/ fsockopen created PHP resource
  • Socket Resource: A socket_create resource, but you must enable socket support at compile time
  • Object: A Swoole\Process Or Swoole\Client, these are automatically converted to a UnixSocket for a process and a client uses socket(Swoole\Client)

Example

<?php

$fp = stream_socket_client("tcp://www.swoole.co.uk.com:80", $errno, $errstr, 30);
fwrite($fp,"GET / HTTP/1.1\r\nHost: www.swoole.co.uk\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 fds 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);

});