javascript - 如何使用 Ratchet 从服务器 websocket 向特定客户端发送数据
问题描述
我是 Ratchet 和 websockets 的新手。
我想用 PHP、Javascript 和 Ratchet 创建一个实时应用程序。
我只需要将数据发送给正在使用该应用程序并拥有permissionId === 2
.
这是我的代码服务器端:
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
//protected $customers;
public function __construct() {
echo 'The server is running' . "\n";
$this->clients = new \SplObjectStorage;
//$this->customers = [];
}
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) {
require "../db/config.php";
$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');
$query = "";
$result_to_send = [];
switch ($msg) {
case "get_users":
$query = "SELECT id, name, email FROM users where login_status = 1";
break;
case "get_provinces":
$query = "SELECT prov_id, prov_nome FROM provincie where active = 1";
break;
}
$result_query = mysqli_query($conn_db, $query);
while($row = mysqli_fetch_assoc($result_query)) {
$result_to_send[] = $row;
}
$result_message = array("action" => $msg, "data" => $result_to_send);
foreach ($this->clients as $client) { //here I pass the data to everyone
$client->send(json_encode($result_message));
}
}
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();
}
}
一切正常。唯一的问题是,在该方法中,onMessage
我只想将查询结果发送给拥有 apermissionId === 2
而不是所有人的客户端。
我想我必须在客户端改变一些东西:
conn.onopen = function(e) { //passing variable permissionId
console.log("Connection established!");
};
我想我最后还必须onOpen
在 PHP 的方法中做一些事情来捕获变量permissionId
并将该变量与$conn->resourceId
.
可以帮忙?
解决方案
推荐阅读
- r - 如何根据 X 中的字符将变量 X 拆分为 2 个变量?
- objective-c - 分配给 'void (^)(__strong id 的块指针类型不兼容
)' 来自 'void (^)(TGClipboardGalleryPhotoItem *__strong)' - amazon-web-services - 在 Terraform 中动态添加资源
- python - 创建python虚拟环境3.6
- php - 无法打开 MAMP 服务器
- python - 在 For 循环中使用变量
- nginx - NGINX HTTPS - SSL 证书
- google-docs - 非常频繁您的访问已过期消息
- javascript - 使用包含非 ASCII 字符的 JavaScript 打开文件(德语)
- python-3.x - 使用 bpy 渲染具有顶点颜色的对象或将顶点颜色转换为纹理