-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeartbeat.php
More file actions
67 lines (55 loc) · 1.7 KB
/
Heartbeat.php
File metadata and controls
67 lines (55 loc) · 1.7 KB
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
60
61
62
63
64
65
<?php
declare(strict_types = 1);
namespace SwowCloud\WebSocket;
use Hyperf\Engine\Channel;
use Hyperf\Engine\Coroutine;
use Psr\Container\ContainerInterface;
use Swow\Http\Server\Connection;
class Heartbeat
{
public Channel $channel;
public Sender $sender;
public ?int $timeout = null;
public ?string $message = null;
public function __construct(ContainerInterface $container, ?int $timeout = null, ?string $message = null)
{
$this->sender = new Sender($container);
$this->timeout = $timeout;
$this->message = $timeout;
$this->channel = new Channel();
}
/**
*循环给客户端发送心跳包
* @return void
*/
public function loop() : void
{
Coroutine::create(function ()
{
while (true) {
$this->channel->pop(5); //也可以自定义时间休眠
$connections = FdCollector::getConnections();
foreach ($connections as $connection) {
$this->sender->push($connection->getFd(), $this->message, $this->timeout);
}
//停止循环 代表当前进程已退出
if ($this->channel->isClosing()) {
break;
}
}
});
}
/**
* 向指定连接发送心跳包
*
* @param \Swow\Http\Server\Connection $connection
* @param string $message
* @param null|int $timeout
*
* @return void
*/
public function send(Connection $connection, string $message, ?int $timeout = null) : void
{
$this->sender->push($connection->getFd(), $message, $timeout);
}
}