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
|
namespace Websocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Request implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $data) {
var_dump($this->clients);
$data = json_decode($data);
switch(true) {
case isset($data->{'isWriting'}):
$response = ['isWriting' => $data->{'isWriting'}];
break;
case isset($data->{'newMessage'}):
$response = ['newMessage' => $data->{'newMessage'}];
break;
default:
echo "request invalid/n";
break;
}
$response = json_encode($response);
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($response);
}
}
}
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 occurred: {$e->getMessage()}\n";
$conn->close();
}
} |