/
Socket.class.php
80 lines (68 loc) · 1.86 KB
/
Socket.class.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
abstract class Socket
{
private $socket;
private $read;
private $write;
private $callback = NULL;
private $quit = false;
public function __construct($ip, $port) {
if (($this->socket =
socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'))) == false)
throw new Exception('Cannot create socket.');
if (socket_connect($this->socket, $ip, $port) == false)
throw new Exception(socket_strerror(socket_last_error($this->socket)));
}
public function __destruct() {
socket_close($this->socket);
}
/*
* Abstract methods
*/
abstract public function readable();
abstract public function writable();
abstract public function is_readable();
abstract public function is_writable();
public function read() {
if ($this->quit == false)
return socket_read($this->socket, 1024);
return 0;
}
public function write($str) {
if ($this->quit == false)
return socket_write($this->socket, $str);
return 0;
}
public function setCallback($call) {
$this->callback = $call;
}
public function close()
{
$this->quit = true;
}
public function monitor($tv_sec, $tv_usec = 0) {
$cs = 0;
$e = NULL;
$time = time();
do {
$this->read = array();
$this->write = array();
if ($this->readable())
$this->read = array($this->socket);
if ($this->writable())
$this->write = array($this->socket);
$cs = socket_select($this->read, $this->write, $e, $tv_sec, $tv_usec);
if (is_array($this->read) && in_array($this->socket, $this->read))
$this->is_readable();
if ($this->quit == false
&& is_array($this->write) && in_array($this->socket, $this->write))
$this->is_writable();
if ($this->callback && $this->quit == false && time() - $time >= $tv_sec)
{
$this->{$this->callback}();
$time = time();
}
} while ($this->quit == false);
}
}
?>