Skip to content

Instantly share code, notes, and snippets.

@igorw
Created June 12, 2012 14:56
Show Gist options
  • Save igorw/2918017 to your computer and use it in GitHub Desktop.
Save igorw/2918017 to your computer and use it in GitHub Desktop.
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
/**
* chat.php
* Send any incoming messages to all connected clients (except sender)
*/
class Chat implements MessageComponentInterface {
protected $clients;
protected $i = 0;
public function __construct(React\Zmq\Socket $pull) {
$this->clients = new \SplObjectStorage;
$this->pull = $pull;
$this->pull->on('message', array($this, 'onPullMessage'));
}
public function onOpen(ConnectionInterface $conn) {
$conn->id = ++$i;
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from != $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
public function onPullMessage($message) {
if (preg_match('/KILL (\d+)/', $message, $matches)) {
foreach ($this->clients as $client) {
if ($client->id === (int) $matches[0]) {
$client->close();
}
}
}
}
}
$loop = React\EventLoop\LoopFactory::create();
$socket = new React\Socket\Server($loop);
$socket->listen(8000, '127.0.0.1');
$context = new React\Zmq\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PUSH);
$pull->connect('tcp://127.0.0.1:5555');
// Run the server application through the WebSocket protocol on port 8000
$ws = new WsServer(new Chat($pull)));
$io = new IoServer($ws, $socket, $loop);
$loop->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment