php-WebSocket在Ratchet下建立连接失败

时间:2017-07-24 04:45:46

标签: php websocket ratchet

我是WebSocket协议的新手,也是Ratchet websocket的新手。我只是按照http://socketo.me/docs/hello-world中建议的步骤尝试构建websocket连接。我的代码:

仓/聊天server.php

<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;

    require dirname(__DIR__) . '/vendor/autoload.php';

    ini_set('display_errors', 1);
    error_reporting(E_ALL);

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

    $server->run();
?>

和src / MyApp / Chat.php

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

class Chat implements MessageComponentInterface {
    protected $clients;

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

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

(实际上它们与网站中的代码相同)

我在命令行中打开chat-server.php,等待客户端。在Chrome上,我打开开发者工具,在控制台中输入以下代码:

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

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

按Enter键,显示:enter image description here

它没有显示消息“Connection established!”。 我检查了: enter image description here

enter image description here

它显示待处理?

我去检查服务器端: enter image description here

好像收到了标题?

过了一会儿,它最终会因超时而断开连接: enter image description here

到目前为止,我认为websocket握手没有成功。我倾向于认为服务器没有正确响应,甚至根本没有响应?但是,我不知道哪个部分出了问题。任何熟悉Ratchet Websocket的人都知道如何解决我的问题?

0 个答案:

没有答案