-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathStreamBuffer.php
More file actions
113 lines (88 loc) · 2.56 KB
/
Copy pathStreamBuffer.php
File metadata and controls
113 lines (88 loc) · 2.56 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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace Socket\React\Stream;
use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use Socket\Raw\Socket as RawSocket;
/** @event full-drain */
// based on a copy-pase of React\Stream\Buffer
class StreamBuffer extends EventEmitter implements WritableStreamInterface
{
private $socket;
private $loop;
public $listening = false;
public $softLimit = 2048;
private $writable = true;
private $data = '';
private $lastError = array(
'number' => 0,
'message' => '',
'file' => '',
'line' => 0,
);
public function __construct(RawSocket $socket, LoopInterface $loop)
{
$this->socket = $socket;
$this->loop = $loop;
}
public function isWritable()
{
return $this->writable;
}
public function write($data)
{
if (!$this->writable) {
return;
}
$this->data .= $data;
if (!$this->listening) {
$this->listening = true;
$this->loop->addWriteStream($this->socket->getResource(), array($this, 'handleWrite'));
}
$belowSoftLimit = strlen($this->data) < $this->softLimit;
return $belowSoftLimit;
}
public function end($data = null)
{
if (null !== $data) {
$this->write($data);
}
$this->writable = false;
if ($this->listening) {
$this->on('full-drain', array($this, 'close'));
} else {
$this->close();
}
}
public function close()
{
$this->writable = false;
$this->listening = false;
$this->data = '';
$this->emit('close');
}
public function handleWrite()
{
// if (!is_resource($this->stream) || feof($this->stream)) {
// $this->emit('error', array(new \RuntimeException('Tried to write to closed or invalid stream.')));
// return;
// }
try {
$sent = $this->socket->write($this->data);
}
catch (Exception $e) {
$this->emit('error', array($e));
return;
}
$len = strlen($this->data);
if ($len >= $this->softLimit && $len - $sent < $this->softLimit) {
$this->emit('drain');
}
$this->data = (string) substr($this->data, $sent);
if (0 === strlen($this->data)) {
$this->loop->removeWriteStream($this->socket->getResource());
$this->listening = false;
$this->emit('full-drain');
}
}
}