Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\WebSocket\Server->disconnect(int $fd, int $code = OpenSwoole\WebSocket\Server::WEBSOCKET_CLOSE_NORMAL, string $reason = ''): bool
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.
The closing status code for the client.
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.
If success, it returns true
, otherwise it returns false
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
.
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.
<?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");
});
// ...