-
-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathServer.php
66 lines (51 loc) · 1.64 KB
/
Server.php
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
<?php
namespace React\Socket;
use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
class Server extends EventEmitter implements ServerInterface
{
public $master;
private $loop;
public function __construct(LoopInterface $loop)
{
$this->loop = $loop;
}
public function listen($port, $host = '127.0.0.1')
{
$this->master = @stream_socket_server("tcp://$host:$port", $errno, $errstr);
if (false === $this->master) {
$message = "Could not bind to tcp://$host:$port: $errstr";
throw new ConnectionException($message, $errno);
}
stream_set_blocking($this->master, 0);
$that = $this;
$this->loop->addReadStream($this->master, function ($master) use ($that) {
$newSocket = stream_socket_accept($master);
if (false === $newSocket) {
$that->emit('error', array(new \RuntimeException('Error accepting new connection')));
return;
}
$that->handleConnection($newSocket);
});
}
public function handleConnection($socket)
{
stream_set_blocking($socket, 0);
$client = $this->createConnection($socket);
$this->emit('connection', array($client));
}
public function getPort()
{
$name = stream_socket_get_name($this->master, false);
return (int) substr(strrchr($name, ':'), 1);
}
public function shutdown()
{
$this->loop->removeStream($this->master);
fclose($this->master);
}
public function createConnection($socket)
{
return new Connection($socket, $this->loop);
}
}