gpt4 book ai didi

php - 如何在 PHP 中处理套接字

转载 作者:行者123 更新时间:2023-12-04 16:14:31 26 4
gpt4 key购买 nike

我正在使用 Ratchett使用 PHP 在我的 Web 服务器上创建套接字。

目前我有 A - 服务器, - 查找数据库更改的设备(在 A 中)和 C - 使用 curl 对数据库进行更改的设备(在 A 中)要求。

当前当 C 进行更改 我将更改存储在 上的数据库中A .同时每秒检查一次 A 通过套接字向 发送请求是否有项目在数据库中A 其中 A 返回响应。这是的腰乙 l 资源。我需要一个方法来当 C 对套接字进行更改以更新 .

这是套接字的代码:

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

require "/NAS/notify/db.php";

class Note implements MessageComponentInterface {
protected $clients;

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

public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}

public function onMessage(ConnectionInterface $from, $msg) {
$stack = array();
foreach ($this->clients as $client) {
if ($from === $client) { //current client only
$query = getNotifications($msg);
if($query){
while($row = mysqli_fetch_assoc($query)){
array_push($stack, $row);
deleteNotification($row['id'], $msg);
}
$client->send(json_encode($stack));
}
}
}
}

public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}

public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}

哪里 getNotifications()获取数据库中的更改和 deleteNotification()删除它。

想法:
  • 我想过存储 $client数据库中的对象,以便当 C 使其可以使用的更改 $client->send()但我不认为这是可能的?
  • 我可以有一个 while(true)使用 $query = getNotifications($msg); 循环里面的代码 - 对 来说太糟糕了A .

  • 你还有其他建议吗?或者实现上面的方法。

    最佳答案

    考虑使用发布-订阅模式,其中寻找对象“X”更新的客户端订阅一个主题,然后让服务器在该主题上发布。 Ratchet 可以使用 WAMPv1 处理此问题:http://socketo.me/docs/wamp或者你可以使用 Thruway这是 WAMPv2建立在 Ratchet 之上。

    关于php - 如何在 PHP 中处理套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41104406/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com