-
Notifications
You must be signed in to change notification settings - Fork 210
/
Socket.php
340 lines (292 loc) · 9.01 KB
/
Socket.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
namespace Wrench\Socket;
use InvalidArgumentException;
use Wrench\Exception\SocketException;
use Wrench\Resource;
use Wrench\Util\Configurable;
/**
* Socket class
* Implements low level logic for connecting, serving, reading to, and
* writing from WebSocket connections using PHP's streams.
* Unlike in previous versions of this library, a Socket instance now
* represents a single underlying socket resource. It's designed to be used
* by aggregation, rather than inheritance.
*/
abstract class Socket extends Configurable implements Resource
{
/**
* Default timeout for socket operations (reads, writes)
*
* @var int seconds
*/
const TIMEOUT_SOCKET = 5;
/**
* @var int
*/
const DEFAULT_RECEIVE_LENGTH = '1400';
/**#@+
* Socket name parts
*
* @var int
*/
const NAME_PART_IP = 0;
const NAME_PART_PORT = 1;
/**#@-*/
/**
* @var resource
*/
protected $socket = null;
/**
* Stream context
*/
protected $context = null;
/**
* Whether the socket is connected to a server
* Note, the connection may not be ready to use, but the socket is
* connected at least. See $handshaked, and other properties in
* subclasses.
*
* @var boolean
*/
protected $connected = false;
/**
* The socket name according to stream_socket_get_name
*
* @var string
*/
protected $name;
/**
* Gets the IP address of the socket
*
* @throws \Wrench\Exception\SocketException If the IP address cannot be obtained
* @return string
*/
public function getIp(): string
{
$name = $this->getName();
if ($name) {
return self::getNamePart($name, self::NAME_PART_IP);
} else {
throw new SocketException('Cannot get socket IP address');
}
}
/**
* Gets the name of the socket
*
* @return string
*/
protected function getName(): string
{
if (!isset($this->name) || !$this->name) {
$this->name = @stream_socket_get_name($this->socket, true);
}
return $this->name;
}
/**
* Gets part of the name of the socket
* PHP seems to return IPV6 address/port combos like this:
* ::1:1234, where ::1 is the address and 1234 the port
* So, the part number here is either the last : delimited section (the port)
* or all the other sections (the whole initial part, the address).
*
* @param string $name (from $this->getName() usually)
* @param int <0, 1> $part
* @return string
* @throws SocketException
*/
public static function getNamePart(string $name, int $part): string
{
if (!$name) {
throw new InvalidArgumentException('Invalid name');
}
$parts = explode(':', $name);
if (count($parts) < 2) {
throw new SocketException('Could not parse name parts: ' . $name);
}
if ($part == self::NAME_PART_PORT) {
return end($parts);
} elseif ($part == self::NAME_PART_IP) {
return implode(':', array_slice($parts, 0, -1));
} else {
throw new InvalidArgumentException('Invalid name part');
}
}
/**
* Gets the port of the socket
*
* @throws \Wrench\Exception\SocketException If the port cannot be obtained
* @return int
*/
public function getPort(): int
{
$name = $this->getName();
if ($name) {
return (int)self::getNamePart($name, self::NAME_PART_PORT);
} else {
throw new SocketException('Cannot get socket IP address');
}
}
/**
* Get the last error that occurred on the socket
*
* @return string
*/
public function getLastError(): string
{
if ($this->isConnected() && $this->socket) {
$err = @socket_last_error($this->socket);
if ($err) {
$err = socket_strerror($err);
}
if (!$err) {
$err = 'Unknown error';
}
return $err;
} else {
return 'Not connected';
}
}
/**
* Whether the socket is currently connected
*
* @return bool
*/
public function isConnected(): bool
{
return $this->connected;
}
/**
* @return resource
*/
public function getResource()
{
return $this->socket;
}
public function getResourceId(): int
{
return (int)$this->socket;
}
/**
* @param string $data Binary data to send down the socket
* @throws SocketException
* @return null|int The number of bytes sent or null on error
*/
public function send(string $data): ?int
{
if (!$this->isConnected()) {
throw new SocketException('Socket is not connected');
}
$length = strlen($data);
if ($length == 0) {
return 0;
}
for ($i = $length; $i > 0; $i -= $written) {
$written = @fwrite($this->socket, substr($data, -1 * $i));
if ($written === false) {
return null;
} elseif ($written === 0) {
return null;
}
}
return $length;
}
/**
* Receive data from the socket
*
* @param int $length
* @return string
*/
public function receive(int $length = self::DEFAULT_RECEIVE_LENGTH): string
{
$buffer = '';
$metadata['unread_bytes'] = 0;
$makeBlockingAfterRead = false;
try {
do {
// feof means socket has been closed
// also, sometimes in long running processes the system seems to kill the underlying socket
if (!$this->socket || feof($this->socket)) {
$this->disconnect();
return $buffer;
}
$result = fread($this->socket, $length);
if ($makeBlockingAfterRead) {
stream_set_blocking($this->socket, true);
$makeBlockingAfterRead = false;
}
// fread FALSE means socket has been closed
if ($result === false) {
$this->disconnect();
return $buffer;
}
$buffer .= $result;
// feof means socket has been closed
if (feof($this->socket)) {
$this->disconnect();
return $buffer;
}
$continue = false;
if (strlen($result) == 1) {
// Workaround Chrome behavior (still needed?)
$continue = true;
}
if (strlen($result) == $length) {
$continue = true;
}
// Continue if more data to be read
$metadata = stream_get_meta_data($this->socket);
if ($metadata && isset($metadata['unread_bytes'])) {
if (!$metadata['unread_bytes']) {
// stop it, if we read a full message in previous time
$continue = false;
} else {
$continue = true;
// it makes sense only if unread_bytes less than DEFAULT_RECEIVE_LENGTH
if ($length > $metadata['unread_bytes']) {
// http://php.net/manual/en/function.stream-get-meta-data.php
// 'unread_bytes' don't describes real length correctly.
//$length = $metadata['unread_bytes'];
// Socket is a blocking by default. When we do a blocking read from an empty
// queue it will block and the server will hang. https://bugs.php.net/bug.php?id=1739
stream_set_blocking($this->socket, false);
$makeBlockingAfterRead = true;
}
}
}
} while ($continue);
return $buffer;
} finally {
if ($this->socket && !feof($this->socket) && $makeBlockingAfterRead) {
stream_set_blocking($this->socket, true);
}
}
}
/**
* Disconnect the socket
*
* @return void
*/
public function disconnect(): void
{
if ($this->socket) {
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
}
$this->socket = null;
$this->connected = false;
}
/**
* Configure options
* Options include
* - timeout_socket => int, seconds, default 5
*
* @param array $options
* @return void
*/
protected function configure(array $options): void
{
$options = array_merge([
'timeout_socket' => self::TIMEOUT_SOCKET,
], $options);
parent::configure($options);
}
}