LoginSignup
17
18

More than 5 years have passed since last update.

Ratchetを試す

Last updated at Posted at 2016-03-30

今回はPHPでWebSocketを扱うためのライブラリRatchetのチュートリアルを試してみます。

作業ディレクトリは
php-ratchet/をアプリのルートディレクトリとします
自分の作業環境はcentos6.7をdocker上で動かしています。

composerインストール

以下のコマンドをかましましょう

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

composer.jsonの編集

php-ratchet/composer.json
{
    "autoload": {
        "psr-0": {
            "MyApp": "src"
        }
    },
    "require": {
        "cboden/ratchet": "0.3.*"
    }
}

インストール

php-ratchet> php composer.phar install

Socket接続時の処理を記述する

まずはディレクトリを作成します

php-ratchet> mkdir -p src/MyApp

PHPファイルの作成

php-ratchet> touch src/MyApp/Chat.php

編集

php-ratchet/src/MyApp/Chat.php
<?php
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
        $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();
    }
}

WebSocketサーバーPHPの作成

まずはディレクトリ作成

php-ratchet> mkdir bin

ファイル作成

php-ratchet> touch bin/chat-server.php

編集

php-ratchet/bin/chat-server.php
<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;

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

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

    $server->run();

これで一応Web Socketが使えるようになりました
チュートリアル追ってるだけなんですけど…

使ってみる

以下のコマンドを実行します

php-ratchet> php bin/chat-server.php

そのほかのコンソールで以下のコマンドを実行

telnet localhost 8080

Mac上で直接実行している場合は上のコマンドで大丈夫ですが、僕はdockerのアドレスを叩かないといけないので
こんな感じでした

telnet 192.168.99.100 8080

ポートに関してはdocker runした時のポートによって変わります
僕は8080:80としてしまったのでchat-server.phpのポートを8080から80に変更しておきました

telnetしたコンソールに何か文字を打ってみると、php側のコンソールに入力した文字列がリアルタイムに反映させるのが確認できると思います

ではでは、以上になります

17
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
18