Laravel 当我从我的 JS 客户端发送消息时,websocket 出现错误

Laravel websocket is getting error when i send a message from my JS client

我正在我的 Laravel 应用程序版本 6.2 中构建一个 websocket 服务,并使用 laravel-websockets 包版本 1.3 (https://github.com/beyondcode/laravel-websockets)。

所以,它工作正常,但我正在自定义我的 websocket 以根据文档重新定义 onOpen、onClose、onError 和 onMessage 方法。在此之后,我用客户端测试了所有这些方法,它们仍然可以正常工作(onOpen、onClose、onError),除了 onMessage 方法,最后执行以下异常:

Exception `ErrorException` thrown: `Undefined property: Ratchet\Server\IoConnection::$app`
Unknown app id: exception `ErrorException` thrown: `Undefined property: Ratchet\Server\IoConnection::$app`.

我不知道发生了什么,但这是我自定义的 websocket class 来捕获客户端事件:

<?php

namespace App\Websocket;

use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface;

class Handler implements MessageComponentInterface
{

    public function onOpen(ConnectionInterface $connection)
    {
        // TODO: Implement onOpen() method.
        \Log::debug('ON OPEN');
        // \Log::debug([$connection]);
    }

    public function onClose(ConnectionInterface $connection)
    {
        // TODO: Implement onClose() method.
        \Log::debug('ON CLOSE');
    }

    public function onError(ConnectionInterface $connection, \Exception $e)
    {
        // TODO: Implement onError() method.
        \Log::debug('ON ERROR');
        // \Log::debug([$connection]);
        \Log::debug($e);
    }

    public function onMessage(ConnectionInterface $connection, MessageInterface $msg)
    {
        // TODO: Implement onMessage() method.
        \Log::debug('ON MESSAGE');
    }
}

我在这里找到了答案beyondcode/laravel-websockets issue #342 您必须在 onOpen 方法中创建一个 app 属性的实例,代码如下:

<?php

namespace App\Websocket;

use BeyondCode\LaravelWebSockets\Apps\App;
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface;

class Handler implements MessageComponentInterface
{

    public function onOpen(ConnectionInterface $connection)
    {
        // TODO: Implement onOpen() method.
        \Log::debug('ON OPEN');
        $socketId = sprintf('%d.%d', random_int(1, 1000000000), random_int(1, 1000000000));
        $connection->socketId = $socketId;
        $connection->app = App::findById('YOUR_APP_ID');
    }

    public function onClose(ConnectionInterface $connection)
    {
        // TODO: Implement onClose() method.
        \Log::debug('ON CLOSE');
    }

    public function onError(ConnectionInterface $connection, \Exception $e)
    {
        // TODO: Implement onError() method.
        \Log::debug('ON ERROR');
        // \Log::debug([$connection]);
        // \Log::debug($e);
    }

    public function onMessage(ConnectionInterface $connection, MessageInterface $msg)
    {
        $connection->send('Hello World!');
        // TODO: Implement onMessage() method.
        \Log::debug(['ON MESSAGE', $msg]);
    }
}

当然,您必须自定义一个服务提供者来初始化应用程序套接字数据,这里是文档:Custom App Providers