-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chat.php
64 lines (47 loc) · 2.18 KB
/
Chat.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
<?php
require 'vendor/autoload.php';
//use Ratchet\MessageComponentInterface;
use Ratchet\WebSocket\MessageComponentInterface; //for binary msgs
use Ratchet\RFC6455\Messaging\MessageInterface; //for binary msgs
use Ratchet\ConnectionInterface;
use MessagePack\Packer;
use MessagePack\BufferUnpacker;
class Chat implements MessageComponentInterface {
protected $clients;
protected $playerData = array(); // assoc array of player names and locations
public function __construct() {
$this->clients = new \SplObjectStorage; //some PHP data structure
}
public function onOpen(ConnectionInterface $conn) {
//Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
//When the server receives a msg from a client, send it to all other clients
public function onMessage(ConnectionInterface $conn, MessageInterface $msg) {
// add the unique ID of the player to the msg
$type = substr($msg, 6, 1);
if($type == "p") { // if position msg
$json = json_decode($msg, true);
print_r($json);
$playerData[(int)$conn->resourceId] = $json["i"]; // add newpos to playerData
$posmsg = json_encode(array("t"=>"p", "d" => array($conn->resourceId => $json["i"])));
// send msg
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connections' . "\n", $conn->resourceId, $posmsg, $numRecv);
foreach ($this->clients as $client) {
if($conn !== $client) {
$client->send($posmsg); //send the $msg to the $client (method semantics confusing)
}
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occured: {$e->getMessage()}\n";
$conn->close();
}
}