-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_server.php
More file actions
60 lines (53 loc) · 1.36 KB
/
websocket_server.php
File metadata and controls
60 lines (53 loc) · 1.36 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
<?php
session_start();
$id = $_SESSION['user_id'];
require "./vendor/autoload.php";
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\MessageComponentInterface;
class WebSocketServer implements MessageComponentInterface
{
protected $clients;
protected $id;
public function __construct($id)
{
$this->clients = new \SplObjectStorage();
$this->id = $id;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
var_dump($conn);
echo "New connection! ({$conn->id})\n";
}
public function onMessage(ConnectionInterface $from, $msg)
{
foreach ($this->clients as $client) {
if ($client !== $from) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
echo "Connection {$conn->id} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
echo "An error occurred: {$e->getMessage()}\n";
$conn->close();
}
}
// Set up the WebSocket server
$server = IoServer::factory(
new HttpServer(
new WsServer(
new WebSocketServer($id)
)
),
5001
);
$server->run();