gpt4 book ai didi

php - 通过 Ratchet\ReactPHP 发送 Action 的状态更新

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

我有一个安全的 websocket 设置并使用 Ratchet 和 ReactPHP 的组合。我想要完成的部分工作是允许用户执行一些将发送到服务器的操作,并获得每个部分完成的通知 - 大致如下:

public function process()
{
$this->currentconnection->send("Doing 1 of 3");
// action first part of process
$this->currentconnection->send("Doing 2 of 3");
// uses output of first part to perform second
$this->currentconnection->send("Doing 3 of 3");
// uses output of second to perform third
$this->currentconnection->send("Complete!");
}
然而,这有效地创建了一个阻塞函数,因为当它运行时,直到函数完成处理,消息才会发送到连接。
以前,我通过在浏览器和 PHP 后端之间来回的 ajax 请求来完成此操作,但我认为我可以在没有来回的情况下完成此操作并使用 websocket(我用于其他功能) ) 来实现这一点。
我一直在查看示例并尝试不同的方法来尝试实现这一目标,但我真的很挣扎,找不到任何其他地方可以实现的示例。现在感觉就像我需要将它作为子进程运行然后(以某种方式)轮询它,但我发现这也很棘手。
因此,如果有人有建议、示例逻辑或我应该在哪里创建可以报告其过程的异步函数/类的指针,那将是惊人的。谢谢你。

最佳答案

我设法通过使用 $loop->futureTick 解决了我的问题功能。我创建了一个类,其中将操作拆分为多个方法,如果方法结束,它会使用 futureTick 方法来排队下一个操作。我的意思的一个例子如下:

class Actions
{
public function __construct(ConnectionInterface $conn, $loop)
{
$this->connection = $conn;
$this->loop = $loop;
}

public function action1()
{
// ... do action ...
if ($fail) {
$this->connection->send('Action 1 failed');
} else {
$this->connection->send('Action 1 success');
$this->loop->futureTick(function() {
$this->action2();
});
}
}

public function action2()
{
...
$this->loop->futureTick(function() {
$this->action3();
});
}
}
这允许通过循环完成每个操作,并且每次函数完成时都会通知客户端。
这可能不是实现这一目标的理想方式,因此我仍然愿意就是否(例如)将操作创建为单独的过程并在进行过程中告知连接方面的建议持开放态度。我只是不确定目前如何实现。

关于php - 通过 Ratchet\ReactPHP 发送 Action 的状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67111035/

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