Websocket on Ratchet

Ratchet

安裝

目前很多PHP套件都是用 Composer 來安裝,所以先安裝 Composer 是必要的

php -r "readfile('https://getcomposer.org/installer');" | php
mv composer.phar /usr/local/bin/composer

再來用 Composer 安裝 Ratchet

cd <project folder>
composer require cboden/ratchet

設定 Composer.json

{
    "autoload": {
        "psr-4": {
            "MyApp\\": "src\"
        }
    },
    "require": {
        "cboden/ratchet": "^0.3.3"
    }
}

MyApp 是該 Project 的名稱

Websocket Application

<Project Folder>/src/Broadcast.php
<?php    
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Broadcast 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();
    }
}

Application 啓動程式

<Project Folder>/bin/server.php
<?php    
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Broadcast;

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

$server = IoServer::factory(

    new HttpServer(
        new WsServer(
            new Broadcast()
        )
    ),
    8880
);

$server->run();

執行 Application

php bin/server.php 

各種 Client (Web, Android, iOS) 的實作,請看以下文章
Using websockets in native iOS and Android apps

到目前為止,Application 應該會把每個 client 傳送過來的訊息,會即時廣播給其它 client,算是完成了一個簡單的 websocket service。

0 意見:

張貼留言