server.php
). 这很管用。
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\WebSocket\WsServerInterface;
require 'vendor/autoload.php';
require_once 'db.php';
class MyClass implements MessageComponentInterface, WsServerInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
$name = str_replace('/', '', $conn->httpRequest->getUri()->getPath());
$resourceId = $conn->resourceId;
$stmt = $db->prepare("INSERT INTO clients (id, resourceId, name) VALUES (null, :resourceId, :name)");
$stmt->bindParam(':resourceId', $resourceId, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
ConnectDB::closeConnection($db);
echo "Connected (" . $resourceId . ")\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$name = str_replace('/', '', $conn->httpRequest->getUri()->getPath());
$request = json_decode($msg);
if (json_last_error() === JSON_ERROR_NONE) {
require_once 'process.php';
$response = processRequest($msg);
if ($response !== false) {
$from->send($response);
}
} else {
$from->send('JSON error');
$ActionType = 'Connect';
}
echo "Incoming message - " $name "\n";
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Closed\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new MyClass()
)
),
8080
);
$server->run();
我正在保存的ID
$resourceId = $conn->resourceId;
到数据库。
我想做的是另一个php脚本,目前
test.php
它可以通过棘轮向客户发送信息。
这是
测试.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\WebSocket\WsServerInterface;
require 'vendor/autoload.php';
require_once 'db.php';
$to = 119; // hard-coded id, not using database yet
$msg = json_encode(array("test" => "test"));
class Sender implements MessageComponentInterface, ConnectionInterface {
public function send(ConnectionInterface $to, $msg) {
$client = $this->clients[$to];
$client->send($msg);
}
}
Sender::send($to, $msg);
错误:
Fatal error: Declaration of Sender::send() must be compatible with Ratchet\ConnectionInterface::send($data) in test.php on line 20
这不起作用,我不知道这是不是正确的方法。我不想回复传入的消息(当前有效),而是最终从
测试.php
.
棘轮示例(Hello world)基本上使用服务器在客户机之间传递消息。在我的例子中,我只希望服务器与单个客户机来回通信。客户之间从不交谈。还有,表格在
测试.php
不会创建客户机,也不会期望得到答案。
有人能引导我朝着正确的方向直接向客户发送信息吗?