-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.php
More file actions
64 lines (47 loc) · 1.58 KB
/
server.php
File metadata and controls
64 lines (47 loc) · 1.58 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
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
// Make sure composer dependencies have been installed
require __DIR__ . '/vendor/autoload.php';
/**
* chat.php
* Send any incoming messages to all connected clients (except sender)
*/
class MyChat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "\nNew Connection";
}
public function onMessage(ConnectionInterface $from, $msg) {
$message = json_decode($msg);
// when new user login/connect
// add its name to socket object
if($message->action == "login")
{
$from->username = $message->content;
}
$message->username = $from->username;
echo "\nMessage: " . json_encode($message);
foreach ($this->clients as $client) {
//if ($from != $client)
//$client->send($msg);
$client->send(json_encode($message));
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "\nClose Connection";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new MyChat, array('*'));
//$app->route('/echo', new Ratchet\Server\EchoServer, array('*'));
$app->run();