Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Custom exception when doing $server->push() on closed client #5610

Open
MrMeshok opened this issue Dec 10, 2024 · 1 comment

Comments

@MrMeshok
Copy link

In a WebSocket server, if you do push on a disconnected client, you will get an ErrorException with message "Swoole\WebSocket\Server::push(): the connected client of connection[1] is not a websocket client or closed".
It would be nice if instead that was some custom exception so you could catch it.
For example:

$server->on('Message', static function (Server $server, Frame $frame) {
    try {
        $server->push($frame->fd, 'Test');
    } catch (\Swoole\Exception\ConnectionClosed $e) {
        /* do something */
    }
});

For now you can do it like this, which is works, but I think option with custom exception is better and potentially more performant, because push function already checks connection before pushing in to it

$server->on('Message', static function (Server $server, Frame $frame) {
    if ($server->isEstablished($frame->fd)) {
        $server->push($frame->fd, 'Test');
    } else {
        /* do something */
    }
});
@fakharksa
Copy link

fakharksa commented Dec 14, 2024

We prefer second option where we check $server->isEstablished($frame->fd) before $server->push($frame->fd, 'Test'); The reason is: Most of the time we use

    if ($server->isEstablished($frame->fd)) {
        $server->push($frame->fd, 'Test');

... inside a loop in order to broadcast particular data to multiple connections (users), where issuing an Exception on a disconnected client can cause the loop to break resulting in failure to send data to the connections next in queue (to be iterated in next iterations of broadcasting-loop)

In a WebSocket Service a connection may disconnect, close or disconnected at anytime; even during the time when we are iterating through the Broadcasting loop (a around code above). An exception will break the loop and will stop sending data to all other connections (only due to a closed / disconnected connection, in the middle of connections queue). This seems not a good idea.

Disconnection / closing of a Socket connection (from client OR server side) is not actually an Error Or Exception, but an allowable and common operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants