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

时间:2020-04-05 08:05:27

标签: laravel websocket laravel-6 phpwebsocket laravel-websockets

我正在我的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类来捕获客户端事件:

<?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');
    }
}

1 个答案:

答案 0 :(得分:0)

我在这里找到了答案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