-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.php
86 lines (71 loc) · 2.02 KB
/
server.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
81
82
83
84
85
86
<?php
namespace App;
require __DIR__.'/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\{WsConnection, WsServer};
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use SplObjectStorage;
class WebsocketServer implements MessageComponentInterface
{
/**
* @var \SplObjectStorage
*/
private SplObjectStorage $clients;
public function __construct()
{
$this->clients = new SplObjectStorage();
}
public function onOpen(ConnectionInterface $conn): void
{
// Store the new connection to send messages to later
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg): void
{
// Don't log output if ping message
if ('ping' !== $msg) {
/**
* @var \Ratchet\WebSocket\WsConnection $from
*/
$numRecv = count($this->clients) - 1;
echo sprintf(
'Sending message "%s" to %d other connection%s' . "\n",
$msg,
$numRecv,
$numRecv == 1 ? '' : 's'
);
}
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn): void
{
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e): void
{
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$host = '0.0.0.0';
$port = 8089;
echo "host: {$host} \n";
echo "port: {$port} \n";
$server = IoServer::factory(
new HttpServer(
new WsServer(
new WebsocketServer()
)
),
$port
);
echo "Initializing websocket server";
$server->run();