Swoole server callback functions

The swoole is an an high-performance network framework uses an event-driven, asynchronous, non-blocking I/O model makes it scalable and efficient. All the business logic is written in the callback functions of events. When a certain event is triggered, the swoole will call the callback function registered for the event.

There are thirteen types of event listed in the below table of contents.

Table of Contents

onStart

When the swoole server starts, the event start happens and the swoole will call the callback function registered for start in the master process.

Before the start event, the swoole server has proceeded the below operations:

  • Create the manager process
  • Create the worker process
  • Listen on the setted TCP/UDP Port
  • Listen on the timer

After the start event, the reactor will receive event and the client can connect the server

In the callback function registered for start, it only allows to log record and modify the name of process.

The event start and workerstart happen concurrently in different processes and have no precedence.

It is recommended to record the value of $serv->master_pid and $serv->manager_pid into file. If so, you can wirte script to send signal to control the process.

Example

<?php
function onStart(swoole_server $server){

}

onShutdown

The event shutdown happens when the swoole server shutdowns.

Before the event shutdown, these operations below happened:

  • All threads are closed.
  • All the worker processed are closed.
  • The listening on the TCP/UDP ports is closed.
  • The Reactor is closed.

Kill the process forcibly, like kill -9, will not trigger the call of function registered for shutdown. It needs to send SIGTREM by kill -15

Example

<?php
function onShutdown(swoole_server $server)

onWorkerStart

The event workerstart happens when the worker process or task worker process starts.

According to the value of $worker_id, if $worker_id>= $serv->setting['worker_num'], the worker is a task worker process otherwise it is a worker process.

There is no relation between worker_id and pid of process.

Example

<?php
function onWorkerStart(swoole_server $server, int $worker_id)

Usage

<?php
$serv->on('WorkerStart', function ($serv, $worker_id){
    global $argv;
    if($worker_id >= $serv->setting['worker_num']) {
        swoole_set_process_name("php {$argv[0]} task worker");
    } else {
        swoole_set_process_name("php {$argv[0]} event worker");
    }
});

onWorkerStop

This event workerstop happens when the worker process stops.

In the callback function registered for the event workerstop, you can retrieve or release the resource for the worker process which stops.

The abnormal stop of worker process will not trigger the event workerstop, for example, fatal error, core dump

Example

<?php
function onWorkerStop(swoole_server $server, int $worker_id);

onTimer

The event timer happens when the timer expires.

Example

<?php
function onTimer(swoole_server $server, int $interval);

$interval is the interval setted by the timer. You can distinguish the timer by the interval.

The timer is added by the $serv->addtimer.

onConnect

This event connect happens when the new connection comes. And the worker process will call the callback function registered for the event connect.

In the mode UDP, there is only receive event and there is no connect and close event.

Example

<?php
function onConnect(swoole_server $server, int $fd, int $from_id);
  • $fd the id number of client

  • $from_id the id number of reactor thread

onReceive

The event receive happens when the worker process receives the data.

The callback function registered for the event receive will be called in the worker process which has received the data.

Example

<?php
function onReceive(swoole_server $server, int $fd, int $reactor_id, string $data)
  • $server the swoole server object

  • $fd If the swoole server is in TCP mode, it's the id number of client. If the swoole server is in UDP mode, it's the value of client ip which has been calculated by some algorithm.

  • $reactor_id If the swoole server is in TCP mode, it's the id number of reactor thread. If the swoole server is in UDP mode, it's the value of client port which has been calculated by some algorithm.

  • $data the data received from the client. If the configurations about automatic protocal hasn't been setted, the max length of data that worker process could receive is 64KB.

For the TCP mode, the data translated between client and server flows and has no boundary. It needs to set the configurations(eof_check/length_check/http_protocol) about spliting the data into package or process the data into package manually.

onPacket

The event packet happens when the worker process recevice the UDP package.

The callback function registered for event packet is called in the process where the event happens.

Example

<?php
function onPacket(swoole_server $server, string $data, array $client_info)
  • $data the UDP package received

  • $client_info, this data is an array. php Array ( [server_socket] => 4 [server_port] => 9501 [address] => 127.0.0.1 [port] => 47306 )

If the swoole server listens on TCP and UDP port, the callback function onReceive will be called when TCP data is received and the callback function onPacket will be called when UDP data is received.

Data transformation

Transform the data to the $fd and reactor_id of callback function onReceive

<?php
$fd = unpack('L', pack('N', ip2long($addr['address'])))[1];
$reactor_id = ($addr['server_socket'] << 16) + $addr['port'];

onClose

The event close happens when the TCP connection between the client and the server is closed.

The worker process will call the callback function registered for the event close.

Example

<?php
function onClose(swoole_server $server, int $fd, int $reactorId);
  • $server the swoole server object

  • $fd the id number of client

  • $reactorId the id number of reactor thread, when the $reactorId < 0, the connection is closed by server.

onBufferFull

The event bufferfull happens when the buffer watermark is highest.

Example

<?php
function onBufferFull(Swoole\Server $serv, int $fd)
  • Set the configuration server->buffer_high_watermark to control the buffer high watermark
  • When the event bufferfull is triggered, it should not send data to client any more.

onBufferEmpty

The event bufferempty happens when the buffer watermark is lowest.

Example

<?php
function onBufferEmpty(Swoole\Server $serv, int $fd)
  • Set the configuration server->buffer_low_watermark to control the buffer low watermark
  • When the event bufferempty is triggered, it could send data to client.

onTask

The event task happens when the worker process send a task data to task worker processed pool.

The task worker process which has received the task data will call the callback function registered for the event task.

When the task worker process is processing the task, its status is busy and changes to idle after finishing the task.

Example

<?php
function onTask(swoole_server $serv, int $task_id, int $src_worker_id, mixed $data);
  • $serv the swoole server object

  • $task_id the id number of task, the combination of $task_id and $src_worker_id is an unique identification for task

  • $data the task data

Return task result to worker process

In the callback function registered for event task, the return of this function is the result of task and will be sent to the worker process which sent the task. You can also return the result of task by calling swoole_server->finish().

When the worker process has received the task result, the event finish would be triggered and call the function registered for event finish in the worker process.

onFinish

When the task finished, the task result would be sent to worker process and trigger the event finish.

Example

<?php
void onFinish(swoole_server $serv, int $task_id, string $data)
  • $serv the swoole server object

  • $task_id the id number of task

  • $data the result of task

onPipeMessage

When the worker process or task worker process receives the message sent by sendMessage, the event pipeMessage happens.

The callback function registered for event pipeMessage will be called.

Example

<?php
void onPipeMessage(swoole_server $server, int $from_worker_id, string $message);
  • $from_worker_id the id number of worker when the message from

  • $message the message

onWorkerError

When there is error or exception in the worker process or task worker process, the event workererror happens in the manager process.

The callback function registered for event workererror is called in manager process.

Example

<?php
void onWorkerError(swoole_server $serv, int $worker_id, int $worker_pid, int $exit_code, int $signal);
  • $worker_id the id number of worker

  • $worker_pid the pid of worker process

  • $exit_code the exit code of worker process

  • $signal the exit signal of worker process

onManagerStart

The event managerstart happens when the manager process starts.

The callback function registered for event managerstart is called in the manager process.

Example

<?php
void onManagerStart(swoole_server $serv);

onManagerStop

The event managerstop happens when the manager process stops.

The callback function registered for event managerstop is called in the manager process.

Example

<?php
void onManagerStop(swoole_server $serv);

Order of events

  • All the callback functions of events are triggered after the start of swoole server.

  • The last event of swoole server is onShutdown when the swoole server shutdowns.

  • After starting the swoole server, the callback functions of onStart/onManagerStart/onWorkerStart are triggered in different process.

Catch Exception

The swoole doesn't support the set_exception_handler function.

If there is the logic of throwing exception in your code, it must add the try/catch in the very beginning of callback function.

<?php
$serv->on('Timer', function() {
    try
    {
        //some code
    }
    catch(Exception $e)
    {
        //exception code
    }
}

Example

Example of registering event callback functions:

<?php
$server = new swoole_server("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
$server->on('WorkerStart', function($serv, $workerId) {
    var_dump(get_included_files());
});