OpenSwoole Server start

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

Declaration

<?php OpenSwoole\Server->start(): bool

Parameters

none

Return

success

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

Description

Starts the OpenSwoole Server, it will create worker_num + 2 processes by default.

Assuming the default mode has been selected (OpenSwoole\Server::POOL_MODE), the following will happen when the server starts:

  • Main (Master) Process: Runs multiple reactor threads, receive new connections and assign connections to the worker processes, handles networking polling and passing the connections onto the worker threads
  • Manager Process: Manages the worker processes, their lifecycle, restarting them, automatic recovery if a fatal error occurs
  • Worker Processes: worker_num * child processes, these processes handle the requests, incoming data and business logic and returning a respond. A worker process will also handle protocol analysis.

If the server fails to start, false will be returned immediately but if everything is correct, the server will enter the event loop and wait for requests to process. The script won't continue passed $server->start() until the server stops. Execution continues once the server is stopped, where the start function returns 'true'.

Based on the configuration that has been set, the task workers will also be launched, this is set using task_worker_num.

You must register any event callbacks before starting the server.

Example

<?php
$server = new OpenSwoole\Server("127.0.0.1", 9501);

$server->on('connect', function ($server, $fd)
{
    echo "New connection established: #{$fd}.\n";
});

$server->on('receive', function ($server, $fd, $from_id, $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();

Common Problems

  • Bind Issues: The server cannot bind to the set IP address or port, this is due to another process using the same IP and port, kill thaty process or change hostname and port number

  • Missing Callbacks: You must set the minimum event callbacks in order for the server to start and accept requests

  • PHP Fatal Error: Check the console output or log file if one has been set

  • Segmentation Fault: If you run into a seg fault, then you will need to reproduce the error, trace your steps and check the core dump logs for more information, see how to check a core dump

  • No Console Output: By default Swoole will continue to output to the console once started but if you see no output you are either running the server in the background or have started it using the daemonize mode and is running as a background process, so console output is sent to the log files instead

Last updated on September 20, 2022