1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Petrica\StatsdSystem\Statsd\Connection; |
4
|
|
|
|
5
|
|
|
use Domnikl\Statsd\Connection; |
6
|
|
|
|
7
|
|
|
class UdpSocket extends Connection\InetSocket implements Connection |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* the used UDP socket resource |
11
|
|
|
* |
12
|
|
|
* @var resource|null|false |
13
|
|
|
*/ |
14
|
|
|
private $socket; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var bool |
18
|
|
|
*/ |
19
|
|
|
private $isConnected; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* sends a message to the socket |
23
|
|
|
* |
24
|
|
|
* @param string $message |
25
|
|
|
* |
26
|
|
|
* @codeCoverageIgnore |
27
|
|
|
* this is ignored because it writes to an actual socket and is not testable |
28
|
|
|
*/ |
29
|
|
|
public function send($message) |
30
|
|
|
{ |
31
|
|
|
try { |
32
|
|
|
parent::send($message); |
33
|
|
|
} catch (\Exception $e) { |
34
|
|
|
// ignore it: stats logging failure shouldn't stop the whole app |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Manually close current connection |
40
|
|
|
*/ |
41
|
|
|
public function close() |
42
|
|
|
{ |
43
|
|
|
if ($this->isConnected()) { |
44
|
|
|
@fclose($this->socket); |
|
|
|
|
45
|
|
|
$this->isConnected = false; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string $message |
51
|
|
|
*/ |
52
|
|
|
protected function writeToSocket($message) |
53
|
|
|
{ |
54
|
|
|
// suppress all errors |
55
|
|
|
@fwrite($this->socket, $message); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param string $host |
60
|
|
|
* @param int $port |
61
|
|
|
* @param int|null $timeout |
62
|
|
|
* @param bool $persistent |
63
|
|
|
*/ |
64
|
|
|
protected function connect($host, $port, $timeout, $persistent = false) |
65
|
|
|
{ |
66
|
|
|
$errorNumber = null; |
67
|
|
|
$errorMessage = null; |
68
|
|
|
|
69
|
|
|
$url = sprintf("udp://%s", $host); |
70
|
|
|
|
71
|
|
|
if ($persistent) { |
72
|
|
|
$this->socket = @pfsockopen($url, $port, $errorNumber, $errorMessage, $timeout); |
73
|
|
|
} else { |
74
|
|
|
$this->socket = @fsockopen($url, $port, $errorNumber, $errorMessage, $timeout); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
$this->isConnected = true; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* checks whether the socket connection is alive |
82
|
|
|
* |
83
|
|
|
* only tries to connect once |
84
|
|
|
* |
85
|
|
|
* ever after isConnected will return true, |
86
|
|
|
* because $this->socket is then false |
87
|
|
|
* |
88
|
|
|
* @return bool |
89
|
|
|
*/ |
90
|
|
|
protected function isConnected() |
91
|
|
|
{ |
92
|
|
|
return $this->isConnected; |
93
|
|
|
} |
94
|
|
|
} |
If you suppress an error, we recommend checking for the error condition explicitly: