OpenSwoole\Server->on('Start', fn)

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Server->on('start', callable $callback)

Parameters

event

The event callback name.

callback

Callable function.

Return

success

If success, it returns true, otherwise it returns false.

Description

Execute the callback function when the server has started and ready to accept requests/connections. You setup this callback before you start a OpenSwoole server, see the example to see how to properly use this callback.

Before the server Start event, the Server has finished the following:

  • Created the Manager process
  • Created the Worker-Sub processes
  • Listening on the TCP/UDP port that was specified, no connections are accepted until this event returns
  • Started the OpenSwoole Timer process

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 OpenSwoole 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 OpenSwoole\Server::SIMPLE_MODE 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 OpenSwoole\Server::SIMPLE_MODE is deprecated

Example

<?php
$server = new OpenSwoole\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();
Last updated on September 20, 2022