Repository navigation
Expand file tree
/
Copy pathServer.php
More file actions
86 lines (70 loc) · 2.2 KB
/
Copy pathServer.php
File metadata and controls
86 lines (70 loc) · 2.2 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
<?php
namespace Socket\React\Stream;
use React\EventLoop\LoopInterface;
use React\Socket\ServerInterface;
use Evenement\EventEmitter;
use Socket\Raw\Factory as RawFactory;
use Socket\Raw\Socket as RawSocket;
class Server extends EventEmitter implements ServerInterface
{
private $factory;
/**
*
* @var RawSocket
*/
private $socket = null;
private $loop;
public function __construct(LoopInterface $loop, RawFactory $factory = null)
{
$this->loop = $loop;
$this->factory = $factory;
}
public function listen($port, $host = '127.0.0.1')
{
if (strpos($host, ':') !== false) {
// IPv6 addressing has to use square brackets
$host = '[' . $host . ']';
}
$address = 'tcp://' . $host . ':' . $port;
return $this->listenAddress($address);
}
public function listenAddress($address)
{
if ($this->factory === null) {
$this->factory = new RawFactory();
}
$this->socket = $this->factory->createServer($address);
if ($this->socket->getType() !== SOCK_STREAM) {
$this->socket->close();
throw new Exception('Not a stream address scheme');
}
$this->socket->setBlocking(false);
$that = $this;
$socket = $this->socket;
$this->loop->addReadStream($this->socket->getResource(), function() use ($socket, $that) {
$clientSocket = $socket->accept();
$that->handleConnection($clientSocket);
});
}
public function handleConnection(RawSocket $clientSocket)
{
$clientSocket->setBlocking(false);
$client = $this->createConnection($clientSocket);
$this->emit('connection', array($client));
}
protected function createConnection(RawSocket $clientSocket)
{
return new Connection($clientSocket, $this->loop);
}
public function getPort()
{
$name = $this->socket->getSockName();
return (int) substr(strrchr($name, ':'), 1);
}
public function shutdown()
{
$this->loop->removeReadStream($this->socket->getResource());
$this->socket->shutdown();
$this->socket->close();
}
}