WebSocket不能建立到服务器的连接

时间:2022-10-28 07:25:05

I try to make a simple chat page on my symfony project by WebSocket. First I used React-php library, it perfectly works on terminal but when I try to connect it to browser I faced this error on chrome:

我试着在我的symfony项目的WebSocket上做一个简单的聊天页面。首先,我使用了反应式-php库,它在终端上非常好用,但当我尝试将它连接到浏览器时,我在chrome上遇到了这个错误:

Uncaught Error: INVALID_STATE_ERR: DOM Exception 11

and on firefox

和火狐

Firefox can't establish a connection to the server at ws://localhost:8000/.

Next I used Ratchet library and follow the tutorial but still the same problem, work on terminal, error on browser. I use telnet localhost 8000 on terminal and javascript on browser is

接下来,我使用棘轮库并遵循教程,但仍然是同样的问题,在终端上工作,在浏览器上出错。终端使用telnet localhost 8000,浏览器使用javascript

var conn = new WebSocket('ws://localhost:8000');
conn.onmessage = function(e) {
    console.log(e.data);
};
conn.send('Hello World!');

the server code for React

响应的服务器代码

require __DIR__.'/../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$conns = new \SplObjectStorage();
$socket->on('connection', function ($conn) use ($conns) {
    $conns->attach($conn);
    $conn->on('data', function ($data) use ($conns, $conn) {
        foreach ($conns as $current) {
            if ($conn === $current) {
                continue;
            }
            $current->write($data);
        }
    });
    $conn->on('end', function () use ($conns, $conn) {
        $conns->detach($conn);
    });
});
$socket->listen(8000);
$loop->run();

and server code for Ratchet

和棘轮的服务器代码

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/chat.php';
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
$server = IoServer::factory( new WsServer( new Chat() ), 8000);
$server->run();

Another thing is client page url is localhost/X/chat and server localhost/X/server, I tried ws://localhost:8000/X/server but still doesn't work

另一件事是客户端页面url是localhost/X/chat和服务器localhost/X/server,我尝试了ws://localhost:8000/X/server,但是仍然不能工作

2 个解决方案

#1


1  

You cannot call send before the connection is established. You need to bind to the onopen event:

在建立连接之前不能调用send。您需要绑定到onopen事件:

var conn = new WebSocket('ws://localhost:8000');
conn.onmessage = function(e) {
    console.log(e.data);
};
conn.onopen = function () {
    conn.send('Hello World!');
};

This should fix your issue.

这应该能解决你的问题。

#2


1  

The problem was in cURL ext. solved.

问题出在cURL上,解决了。

#1


1  

You cannot call send before the connection is established. You need to bind to the onopen event:

在建立连接之前不能调用send。您需要绑定到onopen事件:

var conn = new WebSocket('ws://localhost:8000');
conn.onmessage = function(e) {
    console.log(e.data);
};
conn.onopen = function () {
    conn.send('Hello World!');
};

This should fix your issue.

这应该能解决你的问题。

#2


1  

The problem was in cURL ext. solved.

问题出在cURL上,解决了。