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

Notice: the documentation is suitable for PHP extension swoole until v4.7.1, we only support PHP extension openswoole from v4.7.1

Declaration

<?php
Swoole\Server->on('Close', 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 closing a new connection.

It is possible to determine if the server or client closed the connection, within the Close event callback, the reactor thread ID is passed, if this argument is -1 then it means the server closed the connection, if it is above 0 then the client closed the connection. So you can perform $reactorId < 0 within an if statement to see who closed the connection.

If you have TCP heartbeat polling setup, if a connection is closed due to being idle, the reactor ID will not be -1.

Example

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

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

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

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

$server->on('Receive', function($server, $fd, $reactorId, $data)
{
    $server->send($fd, "Echo to #{$fd}: \n".$data);
    $server->close($fd);
});

$server->on('Close', function($server, $fd, $reactorId)
{
    echo "Connection closed: #{$fd}.\n";
});

$server->start();
  • $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.

Notes

  • If a fatal error occurs within the Close callback, it will cause a memory leak due to connections being in a CLOSE_WAIT state

  • Both a connection being closed by the server or client, it will trigger the Close event callback

  • You can still use the Swoole\Server->getClientInfo method to access information about the client that was connected

  • When this callback is executed it means the connection has already been closed, so you don't need to call $server->close($fd) otherwise it will throw a warning