首页 > 解决方案 > WebSocket:失败:WebSocket 握手期间出错:net::ERR_INVALID_HTTP_RESPONSE

问题描述

我想了解 webSocket,所以我使用 symfony 和 Ratchet 库。

我遵循 Ratchet 的文档,创建了 Chat 类和服务器。当我在 linux 控制台中进行测试时,一切正常,建立了连接,并将消息发送到所有连接的客户端。

但是当我把这个 javascript 代码放在 twig 文件中以在浏览器中测试它时:

<body>
<h1>Websokets chat</h1>


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

conn.onmessage = function(e) {
    console.log(e.data);
};

</script>
</body>

我得到这个错误:

聊天:8 WebSocket 连接到 'ws://localhost:8080/' 失败:WebSocket 握手期间出错:net::ERR_INVALID_HTTP_RESPONSE(匿名)@chat:8

这是运行服务器的命令代码:

<?php
namespace App\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Ratchet\Server\IoServer;
use App\Server\Chat;

class ChatServerCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('hous:app:chat-server')
            ->setDescription('Start chat server');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $server = IoServer::factory(
            new Chat(),
            8080,
            '127.0.0.1'
        );
        $server->run();
    }
}

解决了:

我已经像这样更改了服务器内部的代码:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
        ), 8080);

    $server->run();
}

标签: websocketsymfony4ratchet

解决方案


推荐阅读