-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample_posts.php
More file actions
114 lines (76 loc) · 2.4 KB
/
sample_posts.php
File metadata and controls
114 lines (76 loc) · 2.4 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
include("vendor/autoload.php");
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\WebSocket\WsServer;
class PostsDemo implements MessageComponentInterface {
public $connections = [];
public $subscriptions = [];
public function subscribe($post_id, ConnectionInterface $conn) {
$post_id = intval($post_id);
$conn_id = spl_object_hash($conn);
if(!isset($this->subscriptions[$post_id])) $this->subscriptions[$post_id] = [];
if(!isset($this->connections[$conn_id])) $this->connections[$conn_id] = [];
$this->subscriptions[$post_id][$conn_id] = $conn;
echo "[SUB] Connection {$conn_id} subscribed to post {$post_id}\n";
}
public function broadcast($post_id, $data) {
$post_id = intval($post_id);
$msg = json_encode($data);
if(!isset($this->subscriptions[$post_id])) return;
echo "[BCAST >> {$post_id}] {$msg}\n";
foreach($this->subscriptions[$post_id] as $conn) { /* @var $conn ConnectionInterface */
$conn_id = spl_object_hash($conn);
echo "\t[CLID::{$conn_id}] Sending... ";
$conn->send($msg);
echo "OK!\n";
}
}
public function onMessage(ConnectionInterface $conn, $msg) {
echo "[RECV] {$msg}\n";
$data = json_decode($msg);
switch($data->event) {
case "subscribe":
$this->subscribe($data->post_id, $conn);
break;
case "post_update":
$this->onPostUpdate($conn, $data);
break;
default: return;
}
}
public function onPostUpdate(ConnectionInterface $conn, $data) {
if(!isset($data->post)) $conn->close();
if($data->token != "my_secret_token") $conn->close();
$this->broadcast($data->post->id, [
'event' => 'post_update',
'post' => $data->post,
]);
}
public function onClose(ConnectionInterface $conn) {
$conn_id = spl_object_hash($conn);
if(!isset($this->connections[$conn_id])) return;
foreach($this->connections[$conn_id] as $post_id) {
unset($this->subscriptions[intval($post_id)][$conn_id]);
}
unset($this->connections[$conn_id]);
}
// ----------------------------------------
public function onOpen(ConnectionInterface $conn) {}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "Error: {$e->getMessage()}\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new PostsDemo()
)
),
8080
);
echo "Starting server on port 8080...\n";
$server->run();