Skip to content

Commit 8ad7e71

Browse files
committed
Add Buffer skeleton
1 parent b783609 commit 8ad7e71

File tree

2 files changed

+51
-6
lines changed

2 files changed

+51
-6
lines changed

Datagram/Buffer.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
namespace Datagram;
4+
5+
use React\EventLoop\LoopInterface;
6+
7+
class Buffer
8+
{
9+
private $loop;
10+
private $socket;
11+
private $listening = false;
12+
private $outgoing = array();
13+
14+
public function __construct(LoopInterface $loop, $socket)
15+
{
16+
$this->loop = $loop;
17+
$this->socket = $socket;
18+
}
19+
20+
public function send($data, $remoteAddress = null)
21+
{
22+
$this->outgoing []= array($data, $remoteAddress);
23+
24+
if (!$this->listening) {
25+
$this->loop->addWriteStream($this->socket, array($this, 'handleWrite'));
26+
$this->listening = true;
27+
}
28+
}
29+
30+
public function handleWrite()
31+
{
32+
list($data, $remoteAddress) = array_shift($this->outgoing);
33+
34+
if ($remoteAddress === null) {
35+
fwrite($this->socket, $data);
36+
} else {
37+
stream_socket_sendto($this->socket, $data, 0, $remoteAddress);
38+
}
39+
40+
if (!$this->outgoing) {
41+
$this->loop->removeWriteStream($this->socket);
42+
$this->listening = false;
43+
}
44+
}
45+
}

Datagram/Socket.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,17 @@ class Socket extends EventEmitter implements SocketInterface
1010
protected $loop;
1111
protected $socket;
1212

13+
protected $buffer;
14+
1315
public $bufferSize = 65536;
1416

1517
public function __construct(LoopInterface $loop, $socket)
1618
{
1719
$this->loop = $loop;
1820
$this->socket = $socket;
1921

22+
$this->buffer = new Buffer($loop, $socket);
23+
2024
$this->resume();
2125
}
2226

@@ -37,13 +41,9 @@ public function getHost()
3741
return trim(substr($address, 0, strrpos($address, ':')), '[]');
3842
}
3943

40-
public function send($data, $target = null)
44+
public function send($data, $remoteAddress = null)
4145
{
42-
if ($target === null) {
43-
fwrite($this->socket, $data);
44-
} else {
45-
stream_socket_sendto($this->socket, $data, 0, $target);
46-
}
46+
$this->buffer->send($data, $remoteAddress);
4747
}
4848

4949

0 commit comments

Comments
 (0)