|
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\Io; |
|
11
|
|
|
|
|
12
|
|
|
use AsyncSockets\Exception\AcceptException; |
|
13
|
|
|
use AsyncSockets\Frame\AcceptedFrame; |
|
14
|
|
|
use AsyncSockets\Frame\FramePickerInterface; |
|
15
|
|
|
use AsyncSockets\Frame\RawFramePicker; |
|
16
|
|
|
use AsyncSockets\Socket\SocketInterface; |
|
17
|
|
|
use AsyncSockets\Socket\UdpClientSocket; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Class DatagramServerIo |
|
21
|
|
|
*/ |
|
22
|
|
|
class DatagramServerIo extends AbstractServerIo |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* Flag whether it is local file socket |
|
26
|
|
|
* |
|
27
|
|
|
* @var bool |
|
28
|
|
|
*/ |
|
29
|
|
|
private $isLocalIo; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* DatagramServerIo constructor. |
|
33
|
|
|
* |
|
34
|
|
|
* @param SocketInterface $socket Socket object |
|
35
|
|
|
* @param bool $isLocal Flag, whether it is local socket |
|
36
|
|
|
*/ |
|
37
|
4 |
|
public function __construct(SocketInterface $socket, $isLocal) |
|
38
|
|
|
{ |
|
39
|
4 |
|
parent::__construct($socket); |
|
40
|
4 |
|
$this->isLocalIo = $isLocal; |
|
41
|
4 |
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** {@inheritdoc} */ |
|
44
|
3 |
|
public function read(FramePickerInterface $picker) |
|
45
|
|
|
{ |
|
46
|
3 |
|
stream_socket_recvfrom( |
|
47
|
3 |
|
$this->socket->getStreamResource(), |
|
48
|
3 |
|
self::SOCKET_BUFFER_SIZE, |
|
49
|
3 |
|
STREAM_PEEK, |
|
50
|
|
|
$remoteAddress |
|
51
|
3 |
|
); |
|
52
|
|
|
|
|
53
|
3 |
|
if (!$remoteAddress && !$this->isLocalIo) { |
|
54
|
1 |
|
stream_socket_recvfrom($this->socket->getStreamResource(), self::SOCKET_BUFFER_SIZE); |
|
55
|
1 |
|
throw new AcceptException($this->socket, 'Can not accept client: failed to receive remote address.'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
2 |
|
$reader = new DatagramClientIo($this->socket, $this->isLocalIo ? null : $remoteAddress); |
|
59
|
2 |
|
return new AcceptedFrame( |
|
60
|
2 |
|
$remoteAddress, |
|
61
|
2 |
|
new UdpClientSocket( |
|
62
|
2 |
|
$this->socket, |
|
63
|
2 |
|
$remoteAddress, |
|
64
|
2 |
|
$reader->read(new RawFramePicker()) |
|
65
|
2 |
|
) |
|
66
|
2 |
|
); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|