onClose

Description:

callback Worker::$onClose

This is a callback function triggered when a client connection disconnects from Workerman. It will be triggered regardless of how the connection is terminated; as long as it is disconnected, onClose will be triggered. Each connection will only trigger onClose once.

Note: If the disconnection is due to extreme situations such as network failure or power outage, Workerman may not be able to immediately send a TCP FIN packet to indicate the disconnection, thus it cannot determine that the connection has been closed and cannot timely trigger onClose. This situation needs to be addressed through application-layer heartbeats. For the implementation of heartbeats in Workerman connections, please refer to here. If you are using the GatewayWorker framework, you can directly use the heartbeat mechanism of the GatewayWorker framework, refer to here.

Since UDP is connectionless, when using UDP, the onConnect callback will not be triggered, nor will the onClose callback.

Callback function parameters

$connection

This is the connection object, namely the TcpConnection instance, which is used to operate on the client connection, such as sending data, closing the connection, etc.

Example

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:8484');
$worker->onClose = function(TcpConnection $connection)
{
    echo "connection closed\n";
};
// Run worker
Worker::runAll();

Tip: In addition to using an anonymous function as a callback, you can also refer to here for alternative callback formats.