Swoole\Server->on('Connect', fn)

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Server->on('Connect', callable $callback)

Parameters

event

The event callback name.

callback

Callable event function.

Return

success

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

Description

Execute the callback function when the Server is accepting a new connection allowing you to perform actions when a new connection appears.

This callback will receive the Swoole server object, the $fd (file descriptor) number of the client connection and the reactor thread process ID where the connection is located.

Both the Connect and Close events are executed within the same process space, the same worker thread. For UDP servers only, there is no on Connect event, just Receive.

When using dispatch modes 1 or 3, Connect, Receive and Close events may be delivered to different processes, so connection related PHP objects may not be accessible in some cases. And the three mentioned events may be executed concurrently in dispatch modes 1 or 3, which may cause unexpected results or exceptions.

Example

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

$server->on('Start', function ($server)
{
    echo "Server has started.\n";
});

$server->on('Shutdown', function ($server)
{
    echo "Server is shutting down.\n";
});

// The onConnect event receives the server object, client fd and reactor process ID
$server->on('Connect', function (Swoole\Server $server, int $fd, int $reactorId)
{
    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 August 31, 2022