Debian Codegraph @

vendor/react/datagram/src/Buffer.php

raw
1 <?php
2
3 namespace React\Datagram;
4
5 use Evenement\EventEmitter;
6 use React\EventLoop\LoopInterface;
7 use \Exception;
8
9 class Buffer extends EventEmitter
10 {
11 protected $loop;
12 protected $socket;
13
14 private $listening = false;
15 private $outgoing = array();
16 private $writable = true;
17
18 public function __construct(LoopInterface $loop, $socket)
19 {
20 $this->loop = $loop;
21 $this->socket = $socket;
22 }
23
24 public function send($data, $remoteAddress = null)
25 {
26 if ($this->writable === false) {
27 return;
28 }
29
30 $this->outgoing []= array($data, $remoteAddress);
31
32 if (!$this->listening) {
33 $this->handleResume();
34 $this->listening = true;
35 }
36 }
37
38 public function onWritable()
39 {
40 list($data, $remoteAddress) = \array_shift($this->outgoing);
41
42 try {
43 $this->handleWrite($data, $remoteAddress);
44 }
45 catch (Exception $e) {
46 $this->emit('error', array($e, $this));
47 }
48
49 if (!$this->outgoing) {
50 if ($this->listening) {
51 $this->handlePause();
52 $this->listening = false;
53 }
54
55 if (!$this->writable) {
56 $this->close();
57 }
58 }
59 }
60
61 public function close()
62 {
63 if ($this->socket === false) {
64 return;
65 }
66
67 $this->emit('close', array($this));
68
69 if ($this->listening) {
70 $this->handlePause();
71 $this->listening = false;
72 }
73
74 $this->writable = false;
75 $this->socket = false;
76 $this->outgoing = array();
77 $this->removeAllListeners();
78 }
79
80 public function end()
81 {
82 $this->writable = false;
83
84 if (!$this->outgoing) {
85 $this->close();
86 }
87 }
88
89 protected function handlePause()
90 {
91 $this->loop->removeWriteStream($this->socket);
92 }
93
94 protected function handleResume()
95 {
96 $this->loop->addWriteStream($this->socket, array($this, 'onWritable'));
97 }
98
99 protected function handleWrite($data, $remoteAddress)
100 {
101 $errstr = '';
102 \set_error_handler(function ($_, $error) use (&$errstr) {
103 // Match errstr from PHP's warning message.
104 // stream_socket_sendto(): Message too long\n
105 $errstr = \trim($error);
106 });
107
108 if ($remoteAddress === null) {
109 // do not use fwrite() as it obeys the stream buffer size and
110 // packets are not to be split at 8kb
111 $ret = \stream_socket_sendto($this->socket, $data);
112 } else {
113 $ret = \stream_socket_sendto($this->socket, $data, 0, $remoteAddress);
114 }
115
116 \restore_error_handler();
117
118 if ($ret < 0 || $ret === false) {
119 throw new Exception('Unable to send packet: ' . $errstr);
120 }
121 }
122 }