-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathsubscribe.php
59 lines (54 loc) · 1.58 KB
/
subscribe.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
declare(strict_types=1);
/**
* This file is part of Simps.
*
* @link https://simps.io
* @document https://doc.simps.io
* @license https://github.com/simple-swoole/simps/blob/master/LICENSE
*/
require __DIR__ . '/vendor/autoload.php';
use Simps\Client\MQTTClient;
$config = [
'host' => '127.0.0.1',
'port' => 9501,
'time_out' => 5,
'username' => 'user03',
'password' => 'hLXQ9ubnZGzkzf',
'client_id' => 'd812edc1-18da-2085-0edf-a4a588c296d1',
'keepalive' => 10,
];
Co\run(function () use ($config) {
$client = new MQTTClient($config, ['open_mqtt_protocol' => true, 'package_max_length' => 30 * 1024 * 1024]);
$will = [
'topic' => 'swoole-mqtt/user03/update',
'qos' => 1,
'retain' => 0,
'content' => '123',
];
while (! $client->connect(true, $will)) {
\Swoole\Coroutine::sleep(3);
$client->connect(true, $will);
}
$topics['swoole-mqtt/user03/get'] = 1;
$topics['swoole-mqtt/user03/update'] = 1;
$timeSincePing = time();
$client->subscribe($topics);
while (true) {
$buffer = $client->recv();
var_dump($buffer);
if ($buffer && $buffer !== true) {
$timeSincePing = time();
}
if (isset($config['keepalive']) && $timeSincePing < (time() - $config['keepalive'])) {
$buffer = $client->ping();
if ($buffer) {
echo '发送心跳包成功' . PHP_EOL;
$timeSincePing = time();
} else {
$client->close();
break;
}
}
}
});