OpenSwoole\WebSocket\Server->disconnect()

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

Declaration

<?php OpenSwoole\WebSocket\Server->disconnect(int $fd, int $code = OpenSwoole\WebSocket\Server::WEBSOCKET_CLOSE_NORMAL, string $reason = ''): bool

Parameters

fd

The file descriptor of the WebSocket connection you want to disconnect and close. Send a close frame to the client. This fd must be a WebSocket connection only.

code

The closing status code for the client.

reason

You may provide a reason for closing the client connection. It must be a UTF-8 formatted string that does not exceed 125 bytes. This parameter is optional.

Return

If success, it returns true, otherwise it returns false

Description

Disconnect the connection from server side, sends a closing frame to the client with the set status code and reason (if a reason is given).

This method will return true if successful but false when something goes wrong or if the status code is incorrect/ not valid.

Calling this method with the $fd of the client you want to disconnect (Can be found from the server event parameters), actively removes the client from the server. When specifying a status code, you may also use integers, so you can select a WebSocket status code between 4000 - 4999 or just 1000 for the default value of OpenSwoole\WebSocket\Server::WEBSOCKET_CLOSE_NORMAL.

Status Codes

For a full list of closing status codes that you can use, Mozilla has a good table to explain everything, you may use the same interger codes with the $code parameter.

Example

<?php

// Server setup...

$server->on('Receive', function($server, $fd, $threadId, $data)
{
    $dataFrame = OpenSwoole\WebSocket\Server::unpack($data);

    if($dataFrame === false)
    {
        echo "Data failed to parse\n";
        $server->send($fd, "Parsing error with: $data\n\n");
    }

    // Some condition to check validity of incoming data...
    if(...)
    {
      // 1003 = data given is not in correct format
      OpenSwoole\WebSocket\Server->disconnect($fd, 1003, 'Unsupported Data Sent');
    }

    echo "Data successfully parsed and received:\n";
    $server->send($fd, $dataFrame->data . "\n\n");
});

// ...
Last updated on September 20, 2022