Repository navigation
Expand file tree
/
Copy pathTcpSocket.php
More file actions
68 lines (63 loc) · 2 KB
/
Copy pathTcpSocket.php
File metadata and controls
68 lines (63 loc) · 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
<?php
class TcpSocket extends Socket {
protected $writebuffer;
protected $is_server = false;
public function init() {
parent::init();
$this->factory = get_class($this);
}
//client
public function write($data) {
if(feof($this->fd)) {
return;
}
if (empty($this->writebuffer))
$this->event_loop->registerSocket($this, EventLoop::EV_READ | EventLoop::EV_WRITE);
$this->writebuffer .= $data;
$this->emit('SocketWrite');
}
public function onSocketWrite() {
$writecount = fwrite($this->fd, $this->writebuffer);
$this->writebuffer = substr($this->writebuffer, $writecount);
if (empty($this->writebuffer)) {
$this->event_loop->registerSocket($this, EventLoop::EV_READ);
$this->emit('WriteBufferEmpty');
}
}
public function onSocketRead() {
if($this->is_server) {
$this->emit('Accept');
return;
}
if(feof($this->fd)) {
$this->close();
return;
}
$data = fread($this->fd, 10240);
$this->emit('Read', $data);
}
public function close() {
$this->event_loop->removeSocket($this);
fclose($this->fd);
}
//server
public function listen($port, $interface = '0.0.0.0') {
$this->is_server = true;
$this->fd = stream_socket_server($interface.":".$port);
stream_set_blocking($this->fd, 0);
//TODO check fd error
if (!is_resource($this->fd)) {
//call error
var_dump("is not resource!!!");
}
$this->event_loop->registerSocket($this, EventLoop::EV_READ);
}
public function onAccept() {
$client_fd = stream_socket_accept($this->fd);
stream_set_blocking($client_fd, 0);
$client = new $this->factory();
$client->fd = $client_fd;
$this->event_loop->registerSocket($client, EventLoop::EV_READ);
$client->emit('Connected');
}
}