Search code examples
phplaravelwebsocketlaravel-websockets

Laravel Websockets Error: (WebSocket is closed before the connection is established)


I am trying to create an RPC WebSocket by using beyondcode/laravel-websockets package in Laravel.

I am able to see the dashboard on laravel-websockets endpoint but when I click connect button it keeps showing me the warning in the console:

WebSocket connection to '<URL>' failed: WebSocket is closed before the connection is established.

TestSockerHandler.php:

<?php

namespace App\Websocket\SocketHandler;


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

class TestSocketHandler implements MessageComponentInterface
{

    function onOpen(ConnectionInterface $conn)
    {
        // TODO: Implement onOpen() method.
        dd($conn->httpRequest);
    }

    function onClose(ConnectionInterface $conn)
    {
        // TODO: Implement onClose() method.
    }

    function onError(ConnectionInterface $conn, \Exception $e)
    {
        // TODO: Implement onError() method.
    }

    public function onMessage(ConnectionInterface $conn, MessageInterface $msg)
    {
        // TODO: Implement onMessage() method.
    }
}

web.php:

\BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter::webSocket('/socket/test', \App\Websocket\SocketHandler\TestSocketHandler::class);

.env:

BROADCAST_DRIVER=pusher
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

PUSHER_APP_ID=livepost
PUSHER_APP_KEY=livepost_key
PUSHER_APP_SECRET=livepost_secret
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT="/etc/letsencrypt/live/mydomain.com/fullchain.pem"
LARAVEL_WEBSOCKETS_SSL_LOCAL_PK="/etc/letsencrypt/live/mydomain.com/privkey.pem"
LARAVEL_WEBSOCKETS_SSL_PASSPHRASE=""
LARAVEL_WEBSOCKETS_PORT=6001

composer.json:

"pusher/pusher-php-server": "7.0.2"
"beyondcode/laravel-websockets": "^1.14"

I am on ubuntu server and defined supervisor for websocket command.

/etc/supervisor/conf.d/websockets.conf:

[program:websockets]
process_name=%(program_name)s
command=sudo php artisan websockets:serve --port=8443
directory=/home/my-app/www
autostart=true
autorestart=true
user=root
redirect_stderr=true
stdout_logfile=/home/my-app/www/storage/logs/websockets.log

supervisor status:

root@my-app:/etc/supervisor/conf.d# supervisorctl status
websockets                       RUNNING   pid 872475, uptime 1:41:26

I already wasted 2 days but couldn't find the reason. Just because there is not any error I don't know what to check or search for. Is there anything that holds error logs or smth? I am checking laravel.log and nginx error.log continuously, but there is not nothing logged about websocket.


Solution

  • For anyone who may have the same problem, I just needed to change the port from 6001 to 8443 in .env file and config/websockets.php.