simps / mqtt

🕹 MQTT Protocol Analysis and Coroutine Client for PHP. Support for 3.1, 3.1.1 and 5.0 versions of the MQTT protocol.
https://mqtt.simps.io
Apache License 2.0
358 stars 58 forks source link

[QUESTION] 关于协程客户端 #37

Closed Dmcz closed 3 years ago

Dmcz commented 3 years ago

SWOOLE不能有多个协程对一个 客户端 进行读 / 写操作。所以将读和写分成了两个协程, 通过channel来做通讯。

但这样似乎对mqtt ack 的处理不太友好。

想问问大佬们是咋处理的。

sy-records commented 3 years ago

现在的就是一一对应的,没使用channel。

Dmcz commented 3 years ago

那也就会导致,监听消息之后。 没法再订阅,发布等操作了。

sy-records commented 3 years ago

这看你代码怎么写了

Dmcz commented 3 years ago
\Hyperf\Utils\Coroutine::create(function() use($timeSincePing) {
    try {
        $client = $this->client();

        while($this->running){
            $buffer = $client->recv();

            if ($buffer && $buffer !== true) {
                $timeSincePing = time();

                $this->onMessage($buffer);
            }

            if ($timeSincePing <= (time() - $client->getConfig()->getKeepAlive())) {
                $buffer = $client->ping();
                if ($buffer) {
                    $this->write('ping success');
                    $timeSincePing = time();
                } else {
                    $client->close();
                    break;
                }
            }

        }

    } catch (\Throwable $th) {
        $this->write('recv coroutine has error: ' . $th->getMessage());
    }

});

我目前只是再协程中 while true 简单的实现了一下。 如果大佬有时间 看能不能 提供个例子参考。

sy-records commented 3 years ago

你用channel也行的,看下这两个吧 https://github.com/hyperf/hyperf/discussions/3260 https://github.com/hyperf/hyperf/discussions/3026

Dmcz commented 3 years ago

ok, thx.