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\Server->on('start', callable $callback)
The event callback name.
Callable function.
If success, it returns true
, otherwise it returns false
.
Execute the callback function when the server has started and ready to accept requests/connections. You setup this callback before you start a Swoole server, see the example to see how to properly use this callback.
Before the server Start
event, the Server has finished the following:
After the Start
event executes, the reactor threads are ready to process server events and accept connections from clients.
In the callback function registered for the Start
event, only limited logic should be executed here, such as logging, recording and modifying the name of process, getting the process ID etc. It is not recommended to run heavy logic in this callback as the server will not be started until this function completes.
The server events Start
and WorkerStart
are started at the same time in different processes. The Start
event is part of the main process thread (Master).
It is recommended to save the value of $server->master_pid
and $server->manager_pid
into a file from Start
callback event function, then you are able to send Linux signals to control these processes later on and monitor their state.
The Master process and worker processes don't share the same memory space, thus, they cannot access each other, so you cannot use a global object that is created within the Start
event, the solution is to either create a global object before starting the server or use Swoole Table to access shared memory between processes.
Because the server won't start until the Start
event callback completes, blocking operations are allowed to be performed here.
The on 'Start' event callback is not available in SWOOLE_BASE
mode because there is no Master process. If you try and use the Start
event you will get the following error:
WARNING swReactorProcess_start: The onStart event with SWOOLE_BASE is deprecated
<?php
$server = new Swoole\Server("127.0.0.1", 9501);
$server->on('Start', function ($server)
{
echo "Server has started.\n";
});
$server->on('Connect', function ($server, $fd)
{
echo "New connection established: #{$fd}.\n";
});
$server->on('Receive', function ($server, $fd, $fromId, $data)
{
$server->send($fd, "Echo to #{$fd}: \n".$data);
$server->close($fd);
});
$server->on('Close', function ($server, $fd)
{
echo "Connection closed: #{$fd}.\n";
});
$server->start();