Не удается подключиться к трещотке - PullRequest
0 голосов
/ 03 мая 2018

Я создал веб-сокет в laravel, когда я запускаю в моем клиенте php-cli artisan websocket: serve, сокет работает нормально, и я могу подключиться к нему через telnet. Когда я пытаюсь подключиться к веб-сокету через js, я получаю эту ошибку.

enter image description here

Мой код выглядит следующим образом
Websocket.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;

class websocket extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'websocket:serve';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a ratchet webscoket';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $server = IoServer::factory(
            new HttpServer(
                new WsServer(
                    new ChatController()
                )
            ),
            8080, "77.104.129.210"
        );

        $server->run();
    }
}

Чат-контроллер

<?php

namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

use Illuminate\Http\Request;

class ChatController implements MessageComponentInterface
{
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
        echo "server is now running";
    }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}

Сокет-клиент

<!DOCTYPE html>
<html>
    <body>

        <h1>WebSocket test</h1>

        <script>
            var conn = new WebSocket('wss://77.104.129.210:8080');
            conn.onopen = function(e) {
                console.log("Connection established!");
            };

            conn.onmessage = function(e) {
                console.log(e.data);
            }
        </script>

    </body>

</html>

Я связался с нашей хостинговой компанией по поводу проблемы, они сказали, что веб-сокеты должны работать нормально, и это должно быть проблемой кодирования. Однако я скопировал проект локально на мой компьютер, и веб-розетка работала нормально, он просто не работает на сервере.

...