Skip to content

Instantly share code, notes, and snippets.

@jbroadway jbroadway/
Created Jun 25, 2013

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:


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.

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 (),
$server->run ();
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
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
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
echo "Connection {$conn->resourceId} has disconnected\n";
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.