Swoole\WebSocket\Server->on('Disconnect', fn)

Declaration

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

Parameters

event

The event name to set a callback for

callback

Callable function for the server event type

Return

If success, it returns true, otherwise it returns false

Description

This function is executed when a WebSocket connection is closed, this could be either by the client or server.

You are not required to register this callback event.

Since v4.7.0

Example

<?php

use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

$server = new Server("0.0.0.0", 9502);

$server->on("Start", function(Server $server)
{
    echo "Swoole WebSocket Server started at http://127.0.0.1:9502\n";
});

$server->on('Open', function(Server $server, Swoole\Http\Request $request)
{
    echo "Connection open: {$request->fd}\n";

    $server->tick(1000, function() use ($server, $request)
    {
        $server->push($request->fd, json_encode(["hello", time()]));
    });
});

$server->on('Message', function(Server $server, Frame $frame)
{
    echo "Received message: {$frame->data}\n";
    $server->push($frame->fd, json_encode(["hello", time()]));
});

$server->on('Close', function(Server $server, int $fd)
{
    echo "Connection close: {$fd}\n";
});

$server->on('Disconnect', function(Server $server, int $fd)
{
    echo "Connection disconnect: {$fd}\n";
});

$server->start();