1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Helix\Socket; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Server that accepts and wraps incoming connections as client instances. |
7
|
|
|
*/ |
8
|
|
|
class StreamServer extends AbstractServer { |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* `SOCK_STREAM` |
12
|
|
|
* |
13
|
|
|
* @return int |
14
|
|
|
*/ |
15
|
|
|
final public static function getType () { |
16
|
|
|
return SOCK_STREAM; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Accepts an incoming client connection. |
21
|
|
|
* This will block unless the server was selected for reading. |
22
|
|
|
* |
23
|
|
|
* @link https://php.net/socket_accept |
24
|
|
|
* |
25
|
|
|
* @see onAccept() |
26
|
|
|
* |
27
|
|
|
* @throws Error |
28
|
|
|
* @return StreamClient The accepted connection, as a client instance. |
29
|
|
|
*/ |
30
|
|
|
public function accept () { |
31
|
|
|
if (!$resource = @socket_accept($this->resource)) { |
32
|
|
|
throw new Error($this->resource); // reliable errno |
33
|
|
|
} |
34
|
|
|
$client = $this->newClient($resource); |
35
|
|
|
$this->onAccept($client); |
36
|
|
|
return $client; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Enables incoming connections. |
41
|
|
|
* Listening without binding first will cause the socket to bind to a random port on *all* network interfaces. |
42
|
|
|
* |
43
|
|
|
* @link https://php.net/socket_listen |
44
|
|
|
* |
45
|
|
|
* @param int $backlog Connection queue size, or `0` to use the system's default. |
46
|
|
|
* @throws Error |
47
|
|
|
* @return $this |
48
|
|
|
*/ |
49
|
|
|
public function listen ($backlog = 0) { |
50
|
|
|
if (!@socket_listen($this->resource, $backlog)) { |
51
|
|
|
throw new Error($this->resource); // reliable errno |
52
|
|
|
} |
53
|
|
|
return $this; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Wraps an accepted connection. |
58
|
|
|
* |
59
|
|
|
* @param resource $resource The accepted connection. |
60
|
|
|
* @return StreamClient |
61
|
|
|
* @throws Error |
62
|
|
|
*/ |
63
|
|
|
protected function newClient ($resource) { |
64
|
|
|
return new StreamClient($resource); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Stub. Called when a client has been accepted. |
69
|
|
|
* |
70
|
|
|
* @param StreamClient $client |
71
|
|
|
* @return void |
72
|
|
|
*/ |
73
|
|
|
protected function onAccept (StreamClient $client) { |
|
|
|
|
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
} |
77
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.