-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.class.php
More file actions
executable file
·482 lines (429 loc) · 11.9 KB
/
Socket.class.php
File metadata and controls
executable file
·482 lines (429 loc) · 11.9 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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
<?php namespace peer;
use io\Channel;
use lang\Value;
/**
* Socket class
*
* @test xp://peer.unittest.sockets.SocketTest
* @see php://network
*/
class Socket implements Channel, Value {
public $host, $port;
public
$_eof = false,
$_sock = null,
$_prefix = 'tcp://',
$_timeout = 60;
protected $context= null;
/**
* Constructor
*
* Note: When specifying a numerical IPv6 address (e.g. fe80::1)
* as value for the parameter "host", you must enclose the IP in
* square brackets.
*
* @param string|peer.net.InetAddress $host either hostname or an IP address
* @param int $port
* @param resource $socket default NULL
*/
public function __construct($host, $port, $socket= null) {
$this->host= (string)$host;
$this->port= $port;
$this->_sock= $socket;
$this->context= stream_context_create();
}
/** @return peer.Sockets */
public function kind() { return Sockets::$STREAM; }
/** @return void */
public function useNoDelay() {
stream_context_set_option($this->context, 'socket', 'tcp_nodelay', true);
}
/**
* Returns remote endpoint
*
* @return peer.SocketEndpoint
*/
public function remoteEndpoint() {
return new SocketEndpoint($this->host, $this->port);
}
/**
* Returns local endpoint
*
* @return peer.SocketEndpoint
* @throws peer.SocketException
*/
public function localEndpoint() {
if ($this->_sock) {
if (false === ($addr= stream_socket_get_name($this->_sock, false))) {
throw new SocketException('Cannot get socket name on '.$this->_sock);
}
return SocketEndpoint::valueOf($addr);
}
return null; // Not connected
}
/**
* Set option on socket context
*
* @param string wrapper 'ssl', 'tcp', 'ftp'
* @param string option
* @param var value
*/
protected function setSocketOption($wrapper, $option, $value) {
stream_context_set_option($this->context, $wrapper, $option, $value);
}
/**
* Retrieve option on socket context
*
* @param string wrapper
* @param string option
* @param var
*/
protected function getSocketOption($wrapper, $option) {
$options= stream_context_get_options($this->context);
return @$options[$wrapper][$option];
}
/**
* Get last error. A very inaccurate way of going about error messages since
* any PHP error/warning is returned - but since there's no function like
* flasterror() we must rely on this
*
* @return string
*/
public function getLastError() {
return isset(\xp::$errors[__FILE__]) ? trim(key(end(\xp::$errors[__FILE__]))) : 'unknown error';
}
/**
* Returns whether a connection has been established
*
* @return bool
*/
public function isConnected() {
if (null === $this->_sock) return false;
// For asynchronously connected sockets, the only way we seem to be able to
// reliably determine connectivity is to look up the remote socket name.
// See https://github.com/reactphp/socket/blob/master/src/TcpConnector.php#L105
if ((stream_context_get_options($this->context)['socket']['flags'] ?? 0) & STREAM_CLIENT_ASYNC_CONNECT) {
if (false === stream_socket_get_name($this->_sock, true)) return false;
}
return true;
}
/**
* Ensures reconnect on clone
*
* @return void
*/
public function __clone() {
if (null === $this->_sock) return;
$options= stream_context_get_options($this->context)['socket'];
$this->close();
$this->establish($options['timeout'] ?? 2.0, $options['flags'] ?? STREAM_CLIENT_CONNECT);
}
/**
* Establish a connection
*
* @see https://github.com/xp-framework/networking/issues/2
* @see php://stream_socket_client
* @param float $timeout
* @param int $flags
* @return bool success
* @throws peer.ConnectException
*/
protected function establish($timeout, $flags) {
$host= (string)$this->host;
if (!$this->_sock= stream_socket_client(
$this->_prefix.('localhost' === $host ? '127.0.0.1' : $host).':'.$this->port,
$errno,
$errstr,
$timeout,
$flags,
$this->context
)) {
$this->_sock= null;
$e= new ConnectException(sprintf(
'Failed connecting to %s:%s within %s seconds [%d: %s]',
$this->host,
$this->port,
$timeout,
$errno,
trim($errstr)
));
\xp::gc(__FILE__);
throw $e;
}
// Remember connection attributes
stream_context_set_option($this->context, 'socket', 'timeout', $timeout);
stream_context_set_option($this->context, 'socket', 'flags', $flags);
$s= (int)$this->_timeout;
stream_set_timeout($this->_sock, $s, (int)(1000 * ($this->_timeout - $s)));
return true;
}
/**
* Open a connection asynchronously. Unlike `connect()`, returns immediately.
*
* @param float $timeout default 2.0
* @return bool
* @throws peer.ConnectException
*/
public function open($timeout= 2.0) {
return null === $this->_sock
? $this->establish($timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT)
: true
;
}
/**
* Open a connection. Waits for it to be completely established before returning.
*
* @param float $timeout default 2.0
* @return bool
* @throws peer.ConnectException
*/
public function connect($timeout= 2.0) {
return null === $this->_sock
? $this->establish($timeout, STREAM_CLIENT_CONNECT)
: true
;
}
/**
* Close socket
*
* @return bool
*/
public function close() {
if (null === $this->_sock) return false;
$res= fclose($this->_sock);
$this->_sock= null;
$this->_eof= false;
return $res;
}
/**
* Set timeout
*
* @param int|float $timeout
*/
public function setTimeout($timeout) {
$this->_timeout= (float)$timeout;
// Apply changes to already opened connection
if ($this->_sock) {
$s= (int)$timeout;
stream_set_timeout($this->_sock, $s, (int)(1000 * ($timeout - $s)));
}
}
/**
* Get timeout
*
* @return float
*/
public function getTimeout() {
return $this->_timeout;
}
/**
* Set socket blocking
*
* @param bool blocking
* @return bool success TRUE to indicate the call succeeded
* @throws peer.SocketException
* @see php://socket_set_blocking
*/
public function setBlocking($blockMode) {
if (false === stream_set_blocking($this->_sock, $blockMode)) {
$e= new SocketException('Set blocking call failed: '.$this->getLastError());
\xp::gc(__FILE__);
throw $e;
}
return true;
}
/**
* Returns whether there is data that can be read
*
* @param float timeout default NULL Timeout value in seconds (e.g. 0.5)
* @return bool there is data that can be read
* @throws peer.SocketException in case of failure
*/
public function canRead($timeout= null) {
if (!$this->_sock) {
throw new SocketException('Socket not connected');
}
$r= [$this->_sock]; $w= null; $e= null;
$n= Sockets::$STREAM->select0($r, $w, $e, $timeout);
return $n > 0;
}
/**
* Reading helper function
*
* @param int maxLen
* @param int type ignored
* @param bool chop
* @return string data
*/
protected function _read($maxLen, $type, $chop= false) {
if (null === $this->_sock) {
throw new SocketException('Read of '.$maxLen.' bytes failed: Socket closed');
}
$res= fgets($this->_sock, $maxLen);
if (false === $res || null === $res) {
// fgets returns FALSE on eof, this is particularily dumb when
// looping, so check for eof() and make it "no error"
if (feof($this->_sock)) {
$this->_eof= true;
return null;
}
$m= stream_get_meta_data($this->_sock);
if ($m['timed_out']) {
$e= new SocketTimeoutException('Read of '.$maxLen.' bytes failed', $this->_timeout);
\xp::gc(__FILE__);
throw $e;
} else {
$e= new SocketException('Read of '.$maxLen.' bytes failed: '.$this->getLastError());
\xp::gc(__FILE__);
throw $e;
}
} else {
return $chop ? chop($res) : $res;
}
}
/**
* Read data from a socket
*
* @param int maxLen maximum bytes to read
* @return string data
* @throws peer.SocketException
*/
public function read($maxLen= 4096) {
return $this->_read($maxLen, -1, false);
}
/**
* Read line from a socket
*
* @param int maxLen maximum bytes to read
* @return string data
* @throws peer.SocketException
*/
public function readLine($maxLen= 4096) {
return $this->_read($maxLen, -1, true);
}
/**
* Read data from a socket (binary-safe)
*
* @param int maxLen maximum bytes to read
* @return string data
* @throws peer.SocketException
*/
public function readBinary($maxLen= 4096) {
if (null === $this->_sock) {
throw new SocketException('Read of '.$maxLen.' bytes failed: Socket closed');
}
$res= fread($this->_sock, $maxLen);
if (false === $res || null === $res) {
$m= stream_get_meta_data($this->_sock);
if ($m['timed_out']) {
$e= new SocketTimeoutException('Read of '.$maxLen.' bytes failed: '.$this->getLastError(), $this->_timeout);
} else {
$e= new SocketException('Read of '.$maxLen.' bytes failed: '.$this->getLastError());
}
\xp::gc(__FILE__);
throw $e;
} else if ('' === $res) {
$m= stream_get_meta_data($this->_sock);
if ($m['timed_out']) {
$e= new SocketTimeoutException('Read of '.$maxLen.' bytes failed: '.$this->getLastError(), $this->_timeout);
\xp::gc(__FILE__);
throw $e;
}
$this->_eof= true;
}
return $res;
}
/**
* Checks if EOF was reached
*
* @return bool
*/
public function eof() {
return $this->_eof;
}
/**
* Write a string to the socket
*
* @param string str
* @return int bytes written
* @throws peer.SocketException in case of an error
*/
public function write($str) {
if (null === $this->_sock) {
throw new SocketException('Write of '.strlen($str).' bytes to socket failed: Socket closed');
}
if (false === ($bytesWritten= fputs($this->_sock, $str, $len= strlen($str)))) {
$e= new SocketException('Write of '.$len.' bytes to socket failed: '.$this->getLastError());
\xp::gc(__FILE__);
throw $e;
}
return $bytesWritten;
}
/**
* Retrieve socket handle
*
* @return resource
*/
public function getHandle() {
return $this->_sock;
}
/**
* Retrieve input stream
*
* @deprecated Use in() instead
* @return io.streams.InputStream
*/
public function getInputStream() {
return $this->in();
}
/**
* Retrieve output stream
*
* @deprecated Use out() instead
* @return io.streams.OutputStream
*/
public function getOutputStream() {
return $this->out();
}
/** @return io.streams.InputStream */
public function in() { return new SocketInputStream($this); }
/** @return io.streams.OutputStream */
public function out() { return new SocketOutputStream($this); }
/**
* Destructor
*
*/
public function __destruct() {
$this->close();
}
/** @return string */
public function toString() {
return sprintf(
'%s(%s -> %s%s:%d)',
nameof($this),
null === $this->_sock ? '(closed)' : (string)$this->_sock,
$this->_prefix,
$this->host,
$this->port
);
}
/** @return string */
public function hashCode() {
return md5($this->_prefix.'>'.$this->host.':'.$this->port);
}
/**
* Compares this socket to another value
*
* @param var $value
* @return int
*/
public function compareTo($value) {
return $value instanceof self
? strcmp(
$this->_prefix.'>'.$this->host.':'.$this->port,
$value->_prefix.'>'.$value->host.':'.$value->port
)
: 1
;
}
}