PHP Ratchet Web套接字发送消息工作流程

时间:2019-02-01 09:25:14

标签: php sockets websocket ratchet

我开发PHP支持瑞奇库聊天服务器,我有一个关于发送消息的疑问:

我有两种方法:find /opt/src/ -path "*/trunk/build.xml" -execdir svn update $(dirname {}) \; -exec ant -f {} \; onOpen(ConnectionInterface $conn)

当客户端连接到聊天时,将调用onOpen方法,并且我将发送响应消息,因此我会onError(ConnectionInterface $conn, \Exception $e)

如果有错误,将调用$conn->send($data),但如果没有错误,我将如何知道是否由于流程继续而一切都成功了? (我没有成功的方法)。

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

我希望是说明问题明确

1 个答案:

答案 0 :(得分:0)

也许,像这样...

@示例:

// ...

/**
 * {@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();
}

玩得开心!

相关问题