1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Async sockets |
4
|
|
|
* |
5
|
|
|
* @copyright Copyright (c) 2015-2016, Efimov Evgenij <[email protected]> |
6
|
|
|
* |
7
|
|
|
* This source file is subject to the MIT license that is bundled |
8
|
|
|
* with this source code in the file LICENSE. |
9
|
|
|
*/ |
10
|
|
|
namespace AsyncSockets\Socket; |
11
|
|
|
|
12
|
|
|
use AsyncSockets\Exception\NetworkSocketException; |
13
|
|
|
use AsyncSockets\Socket\Io\StreamedServerIo; |
14
|
|
|
use AsyncSockets\Socket\Io\DatagramServerIo; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class ServerSocket |
18
|
|
|
*/ |
19
|
|
|
class ServerSocket extends AbstractSocket |
20
|
|
|
{ |
21
|
|
|
/** {@inheritdoc} */ |
22
|
4 |
|
protected function createSocketResource($address, $context) |
23
|
|
|
{ |
24
|
4 |
|
$type = $this->getSocketScheme($address); |
25
|
4 |
|
$resource = stream_socket_server( |
26
|
4 |
|
$address, |
27
|
4 |
|
$errno, |
28
|
4 |
|
$errstr, |
29
|
4 |
|
$this->getServerFlagsByType($type), |
30
|
|
|
$context |
31
|
4 |
|
); |
32
|
|
|
|
33
|
4 |
|
if ($errno || $resource === false) { |
34
|
2 |
|
throw new NetworkSocketException($this, $errstr, $errno); |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
return $resource; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Return socket scheme |
42
|
|
|
* |
43
|
|
|
* @param string $address Address in form scheme://host:port |
44
|
|
|
* |
45
|
|
|
* @return string|null |
46
|
|
|
*/ |
47
|
4 |
|
private function getSocketScheme($address) |
48
|
|
|
{ |
49
|
4 |
|
$pos = strpos($address, '://'); |
50
|
4 |
|
if ($pos === false) { |
51
|
1 |
|
return null; |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
return substr($address, 0, $pos); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Return flags for connection |
59
|
|
|
* |
60
|
|
|
* @param string $scheme Socket type being created |
61
|
|
|
* |
62
|
|
|
* @return int |
63
|
|
|
*/ |
64
|
4 |
|
private function getServerFlagsByType($scheme) |
65
|
|
|
{ |
66
|
|
|
$connectionLessMap = [ |
67
|
4 |
|
'udp' => 1, |
68
|
4 |
|
'udg' => 1, |
69
|
4 |
|
]; |
70
|
|
|
|
71
|
4 |
|
return isset($connectionLessMap[ $scheme ]) ? |
72
|
4 |
|
STREAM_SERVER_BIND : |
73
|
4 |
|
STREAM_SERVER_BIND | STREAM_SERVER_LISTEN; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** {@inheritdoc} */ |
77
|
2 |
|
protected function createIoInterface($type, $address) |
78
|
|
|
{ |
79
|
|
|
switch ($type) { |
80
|
2 |
|
case self::SOCKET_TYPE_UNIX: |
81
|
|
|
return new StreamedServerIo($this); |
82
|
2 |
|
case self::SOCKET_TYPE_TCP: |
83
|
1 |
|
return new StreamedServerIo($this); |
84
|
1 |
|
case self::SOCKET_TYPE_UDG: |
85
|
|
|
return new DatagramServerIo($this, true); |
86
|
1 |
|
case self::SOCKET_TYPE_UDP: |
87
|
|
|
return new DatagramServerIo($this, false); |
88
|
1 |
|
default: |
89
|
1 |
|
throw new \LogicException("Unsupported socket resource type {$type}"); |
90
|
1 |
|
} |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|