棘轮:仍在连接状态

时间:2015-03-17 05:09:34

标签: javascript php websocket composer-php ratchet

我是这个websocket的初学者,我正在为我的第一个项目尝试这个棘轮..

我已在命令提示符中执行此命令,在http://socketo.me中完成了安装教程

composer require cboden/ratchet

之后,它会自动生成vendor个文件夹,其中包含几个库,并在主路径上composer.jsoncomposer.lock

然后我制作了一个chat.php文件并复制了棘轮git上的快速示例中的代码:

<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

    // Make sure composer dependencies have been installed
    require __DIR__ . '/vendor/autoload.php';

/**
 * chat.php
 * Send any incoming messages to all connected clients (except sender)
 */
class MyChat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {
                $client->send($msg);
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        $conn->close();
    }
}

    // Run the server application through the WebSocket protocol on port 8080
    $app = new Ratchet\App('localhost', 8080);
    $app->route('/chat', new MyChat);
    $app->route('/echo', new Ratchet\Server\EchoServer, array('*'));
    $app->run();

然后我在命令提示符下执行此命令:php chat.php

我的客户端仍然有错误说:

Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

火狐 InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

我的folderization(在XAMPP上):

客户端

htdocs/public/chat/index.phpcommon.js完整,包含

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

服务器

htdocs/public/chatserver/chat.php
htdocs/public/chatserver/vendor/<some libraries>
htdocs/public/chatserver/composer.json
htdocs/public/chatserver/composer.lock

我错过了什么吗?

2 个答案:

答案 0 :(得分:9)

请尝试这样:

var conn = new WebSocket('ws://localhost:8080/echo');
conn.onmessage = function(e) { console.log(e.data); };
conn.onopen = function(e) {
    console.log("Connection established!");
    conn.send('Hello Me!');
};

您应该能够在连接打开时发送。似乎是在建立连接之前尝试它。

答案 1 :(得分:0)

我遇到了同样的问题,并使用Troubleshooting A1进行了修复: You missed a step。我确实错过了服务器php中的这一部分

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);