-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.php
More file actions
55 lines (42 loc) · 1.36 KB
/
server.php
File metadata and controls
55 lines (42 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
<?php
namespace App;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class WebSocketServer implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) : void
{
$this->clients->attach($conn);
print "New connection started on socket server ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) : void
{
$count = count($this->clients) - 1;
sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $count, $count == 1 ? '' : 's');
print "Received Message: {$msg}\n";
foreach ($this->clients as $client) :
$client->send($msg);
endforeach;
}
public function onClose(ConnectionInterface $conn) : void
{
$this->clients->detach($conn);
print "Connection ({$conn->resourceId}) closed\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) : void
{
print "Error: ({$e->getMessage()})\n";
$conn->close();
}
}
// Using on server
use Ratchet\App;
$app = new App('localhost', 8000, '0.0.0.0');
$app->route('/ws', new WebSocketServer, ['*']);
$app->run();