【发布时间】:2021-06-26 15:25:14
【问题描述】:
我的服务器代码是 php Ratchet
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Ratchet\Server\IoServer;
use App\BroadCastController;
$server = IoServer::factory(new BroadCastController(),8080);
$server->run();
这个广播控制器
<?php
namespace App;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class BroadCastController 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);
// }
// }
print "\n";
print "====================FROM=========================\n";
print "\n";
print_r(gettype($from));
print "\n";
print "====================MESSSAGE=========================\n";
print "\n";
print_r(gettype($msg));
print "\n";
}
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();
}
}
此客户端 JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var ws = new WebSocket("ws://localhost:8080");
console.log(ws);
ws.onopen = function() {
console.log("open!");
}
ws.onmessage = function(event) {
console.log(event.data);
}
ws.onclose = function() {
console.log("Closed");
}
ws.onerror = function(e) {
console.log(e);
console.log("trouble in paradise");
}
</script>
</body>
</html>
【问题讨论】:
-
console.log ws.readyState 看看是不是1
-
................................................ ......好的
-
.......................我得到 0
-
那么连接就是谎言。尝试连接外部工具,例如:chrome.google.com/webstore/detail/websocket-test-client/…
标签: javascript php websocket phpwebsocket