Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Example of using Ratchet with Elefant

To install Ratchet, add the following line to the "require" section of the composer.json file found in the root of your Elefant site:

"cboden/Ratchet": "0.2.*"

The section should look like this:

"require": {
	"php": ">=5.3.2",
	"cboden/Ratchet": "0.2.*"
}

More info on installing Ratchet is available here.

Next, create the following files based on the ones found in this gist:

apps/chat/handlers/run.php
apps/chat/lib/Server.php

These are based on Ratchet's Hello World example found here.

To run the server, use the following command:

php index.php chat/run

To connect to the server, open two new terminal windows and enter this into both:

telnet localhost 8080

In each of the telnet connections, anything you type should appear in the other window. From here, follow the next steps in the Ratchet documentation for more advanced usage.

<?php
if (! $this->cli) die ('Must be run from the command line!');
$page->layout = false;
require 'lib/vendor/autoload.php';
$server = Ratchet\Server\IoServer::factory (
new chat\Server (),
8080
);
$server->run ();
?>
<?php
namespace chat;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Server implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen (ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$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();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment