3

我尝试通过 WebSocket 在我的 symfony 项目上创建一个简单的聊天页面。首先我使用了React-php库,它在终端上完美运行,但是当我尝试将它连接到浏览器时,我在 chrome 上遇到了这个错误:

Uncaught Error: INVALID_STATE_ERR: DOM Exception 11

在火狐上

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

接下来我使用Ratchet库并按照教程进行操作,但仍然存在同样的问题,在终端上工作,在浏览器上出错。我telnet localhost 8000在终端上使用,浏览器上的 javascript 是

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

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();

和 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();

另一件事是客户端页面网址localhost/X/chat和服务器localhost/X/server,我试过ws://localhost:8000/X/server但仍然无法正常工作

4

3 回答 3

1

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

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

这应该可以解决您的问题。

于 2012-10-28T14:28:45.427 回答
1

问题出在 cURL 分机中。解决了。

于 2012-11-05T16:19:37.720 回答
0

As I understand it, React\Socket opens a plaintext TCP / IP connection.

You can use any plaintext TCP/IP client to connect to your server, such as telnet or any other TCP/IP library.

If you want to use a WebSocket client, such as the one provided by your browser, you will have to use a WebSocket server. Ratchet is a WebSocket server that builds on top of this project.

Look this https://github.com/reactphp/socket/issues/142

于 2020-05-20T16:52:57.427 回答