提问者:小点点

Laravel webSocket得到错误时,我发送消息从我的JS客户端


我正在我的Laravel应用程序版本6.2中构建websocket服务,并使用Laravel websocket软件包版本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`.

我不知道发生了什么,但这里是我自定义web套接字类来捕捉客户端事件:

<?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个答案

匿名用户

我在这里找到了答案,在代码/laravel websockets问题#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]);
    }
}

当然,你必须自定义一个服务提供商来初始化应用程序套接字数据,这里是留档:自定义应用程序提供商