Skip to content

Instantly share code, notes, and snippets.

@cboden
Created June 19, 2012 12:43
Show Gist options
  • Save cboden/2953926 to your computer and use it in GitHub Desktop.
Save cboden/2953926 to your computer and use it in GitHub Desktop.
TempRouter
<?php
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
$router = new TempRouter;
$router->setRoute('/hello', new MyApp1);
$router->setRoute('/world', new MyApp2);
$server = IoServer::factory(new WsServer($router), 80);
$server->run();
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class MyApp1 implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {
}
public function onMessage(ConnectionInterface $from, $msg) {
}
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
}
}
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class MyApp2 implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {
}
public function onMessage(ConnectionInterface $from, $msg) {
}
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
}
}
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class TempRouter implements MessageComponentInterface {
private $routes = array();
public function setRoute($path, MessageComponentInterface $component) {
$this->routes[$path] = $component;
}
public function onOpen(ConnectionInterface $conn) {
if (array_key_exists($conn->WebSocket->request->getPath(), $this->routes)) {
$conn->route = $this->routes[$conn->WebSocket->request->getPath()];
$conn->route->onOpen($conn);
} else {
$conn->close();
}
}
public function onMessage(ConnectionInterface $from, $msg) {
$from->route->onMessage($from, $msg);
}
public function onClose(ConnectionInterface $conn) {
if (isset($conn->route)) {
$conn->route->onClose($conn);
}
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->route->onError($conn, $e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment