【问题标题】:PHP Ratchet web socket send message workflowPHP Ratchet Web 套接字发送消息工作流程
【发布时间】:2019-02-01 09:25:13
【问题描述】:

我正在通过 PHP Ratchet 库开发聊天服务器,但我对发送消息有疑问:

我有两种方法:onOpen(ConnectionInterface $conn)onError(ConnectionInterface $conn, \Exception $e)

当客户端连接到聊天时调用 onOpen 方法,我会发送响应消息,因此我会使用$conn->send($data)

如果有错误onError 被调用,但如果没有错误我如何知道一切是否成功,因为流程仍在继续? (我没有成功的方法)。

我问你以下问题是因为我必须处理以下情况: 当我将消息发送给客户端时,如果“发送”方法出错,我必须将无法发送的消息保存在数据库中并稍后尝试推迟,而如果发送成功,我不必保存任何事物。我的问题是,如果“发送”方法出错,则调用“onError”方法,我只有关于“ConnectionInterface”的实例,但没有我无法发送的消息,那我怎么能?怎么恢复?

我希望我能清楚地解释问题

【问题讨论】:

  • 没人能帮我吗?

标签: php sockets websocket ratchet


【解决方案1】:

也许,有些像这样......

@示例:

// ...

/**
 * {@inheritDoc}
 */
public function onOpen(ConnectionInterface $connection)
{
    // ...

    $package = [
        'data'  => $data = [] // for example
    ];

    $json = json_encode($package, JSON_FORCE_OBJECT);

    $connection->currentMessage = $json;
    $connection->send($json);

    // $connection->send(null); // uncomment if you wanna simulate error (call onError())
}

// ...

/**
 * {@inheritDoc}
 */
public function onError(ConnectionInterface $connection, \Exception $e)
{
    $connection->currentMessage; <-- your current message

    // ... save message, etc, ...whatever you want :)

    $connection->close();
}

玩得开心!

【讨论】:

    猜你喜欢
    • 2017-08-14
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 2017-01-13
    相关资源
    最近更新 更多