-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPingKeepAlive.php
92 lines (77 loc) · 2.13 KB
/
PingKeepAlive.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Nucleus - XMPP Library for PHP
*
* Copyright (C) 2016, Some rights reserved.
*
* @author Kacper "Kadet" Donat <[email protected]>
*
* Contact with author:
* Xmpp: [email protected]
* E-mail: [email protected]
*
* From Kadet with love.
*/
namespace Kadet\Xmpp\Component;
use Kadet\Xmpp\Stanza\Iq;
use Kadet\Xmpp\XmppClient;
use \Kadet\Xmpp\Utils\filter as with;
use React\EventLoop\Timer\TimerInterface;
class PingKeepAlive extends Component
{
/** @var float|int */
private $_interval = 15;
/** @var TimerInterface */
private $_timer;
private $_handler = null;
/**
* PingKeepAlive constructor.
*
* @param float|false $interval Keep alive interval in seconds or false to turn off
*/
public function __construct($interval = 60.)
{
$this->_interval = $interval;
}
public function setClient(XmppClient $client)
{
parent::setClient($client);
$this->_client->on('state', [$this, 'enable'], \Kadet\Xmpp\Utils\filter\equals('ready'));
$this->_handler = $this->_client->on('iq', function(Iq $iq) {
$this->handleIq($iq);
}, with\all(with\iq\query(with\element('ping', 'urn:xmpp:ping')), with\stanza\type('get')));
}
/**
* Starts keep alive timer
*/
public function enable()
{
if($this->_interval) {
$this->_timer = $this->_client->connector->getLoop()->addPeriodicTimer($this->_interval, function() {
$this->keepAlive();
});
}
}
/**
* Stops keep alive timer
*/
public function disable()
{
if($this->_timer) {
$this->_timer->cancel();
}
$this->_client->removeListener('iq', $this->_handler);
}
private function keepAlive()
{
$ping = new Iq('get', ['query' => new Iq\Query('urn:xmpp:ping', 'ping')]);
$this->_client->write($ping);
}
private function handleIq(Iq $iq)
{
$response = $iq->response();
$response->type = 'result';
$response->query = new Iq\Query('urn:xmpp:ping', 'ping');
$this->_client->write($response);
}
}