-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathwebsocket.php
More file actions
90 lines (81 loc) · 3.09 KB
/
websocket.php
File metadata and controls
90 lines (81 loc) · 3.09 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
<?php
namespace App\Services;
(PHP_SAPI !== 'cli' || isset($_SERVER['HTTP_USER_AGENT'])) && die('cli only');
require 'vendor/autoload.php';
use Ratchet\Http\HttpServer;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
class RatchetServer implements MessageComponentInterface
{
protected $clients;
public function start($port)
{
$server = IoServer::factory(
new HttpServer(
new WsServer(
$this
)
),
$port
);
$server->run();
}
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
$conn->roomId = null;
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$data = json_decode($msg, true);
if(is_null($from->roomId)){
if($data['type'] == "createRoom"){
$from->roomId = bin2hex(openssl_random_pseudo_bytes(16));
$from->send(json_encode(["type"=>"createdRoom","content"=>$from->roomId]));
return;
}
if($data['type'] == "joinRoom"){
$joined = false;
foreach ($this->clients as $client)
if ($data['content'] === $client->roomId && $from !== $client)
$joinAnnounceClients[] = $client;
if(count($joinAnnounceClients) == 1){
foreach($joinAnnounceClients as $joinAnnounceClient)
$joinAnnounceClient->send(json_encode(["type"=>"userJoined"]));
$from->roomId = $data['content'];
$from->send(json_encode(["type"=>"joinedRoom"]));
} else {
$from->send(json_encode(["type"=>"error","content"=>"Invalid room ID"]));
}
}
return;
}
foreach ($this->clients as $client) {
if ($from->roomId === $client->roomId && $from !== $client && !is_null($from->roomId)) {
if($data['type'] == 'keyExchange')
$client->send(json_encode(["type"=>"keyExchange","content"=>$data['content']]));
else if($data['type'] == 'message')
$client->send(json_encode(["type"=>"message","content"=>$data['content']]));
}
}
}
public function onClose(ConnectionInterface $conn) {
foreach ($this->clients as $client) {
if ($conn->roomId === $client->roomId && $conn !== $client && !is_null($conn->roomId)) {
$client->send(json_encode(["type"=>"userDisconnect"]));
}
}
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$server = new RatchetServer();
$server->start(8089);