Home > Net >  PHP Websocket. Send message on close?
PHP Websocket. Send message on close?

Time:02-01

I use workerman/workerman for websockets. The main question – how to send messages on websocket closing? Also I tried to send messages to other connections. No result too.

    public function run()
    {
        $this->ws = new Worker(
            'websocket://0.0.0.0:' . $_ENV['WS_PORT'],
            ['ssl' => [
                'local_cert'  => $_ENV['WS_CERTIFICATE_CRT'],
                'local_pk'    => $_ENV['WS_CERTIFICATE_KEY'],
                'verify_peer' => false,
            ]]
        );
        $this->ws->count = 1;
        $this->ws->transport = 'ssl';

        $this->ws->onConnect = function ($connection) {
            $this->onConnect($connection);
        };

        $this->ws->onMessage = function ($connection, $data) {
            $this->onMessage($connection, $data);
        };

        $this->ws->onClose = function ($connection) {
            $this->onClose($connection);
        };

        Worker::runAll();
    }

This doesn't work

private function onClose($connection)
{
    $connection->send("Hello");
}

CodePudding user response:

Looking at the source code of workerman/workerman we can see that the onClose event is implemented as follows:

        // Close socket.
        try {
            @fclose($this->socket);
        } catch (Throwable) {
        }

        $this->status = self::STATUS_CLOSED;
        // Try to emit onClose callback.
        if ($this->onClose) {
            try {
                ($this->onClose)($this);
            } catch (Throwable $e) {
                $this->error($e);
            }
        }

As you can see, onClose is emitted AFTER the socket has been closed.

So you will not be able to use that socket in your onClose handler anymore.

A better solution would be that the client sends some sort of "close" packet to the server.

The server can then run some logic and close the connection after it is done.

  • Related