我是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);
};
它没有显示消息“Connection established!”。 我检查了:
它显示待处理?
好像收到了标题?
到目前为止,我认为websocket握手没有成功。我倾向于认为服务器没有正确响应,甚至根本没有响应?但是,我不知道哪个部分出了问题。任何熟悉Ratchet Websocket的人都知道如何解决我的问题?