Ratchet Websocket PHP – HelloWorld

ratchet is websocket base PHP script,
As Far I Feel as newbie, its hard to understand “HelloWorld” tutorial, the common problem is file structure

lets say, the ‘root document’ is /media/sf_websocket

I am using ubuntu 14 server

download composer.phar https://getcomposer.org/download/

#i am using command

cd /media/sf_websocket

mkdir ws

cd ws

# download composer.phar

curl -sS https://getcomposer.org/installer | php

# create file composer.json

nano composer.json

# input this text

"autoload": {
"psr-0": {
"MyApp": "src"
"require": {
"cboden/ratchet": "0.3.*"

# download ratchet source

php composer.phar install

you will get vendor folder, and composer.lock file


# create folder src/MyApp

mkdir src/MyApp -p

# create file src/MyApp/Chat.php

nano src/MyApp/Chat.php

# paste this code

namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat 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";


# create folder bin

mkdir bin

# create chat-server.php

nano bin/chat-server.php

# paste code

use Ratchet\Server\IoServer;
use MyApp\Chat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
new Chat(),


finish structure


# run server websocket

php /media/sf_websocket/ws/bin/chat-server.php

# test with telnet

telnet localhost 8080

telnet localhost 8080


Published by


just to remember what i had known :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s