一つの課題がありまして、PHPでもうすでにできあがっているプログラムがあり、でもWebsocketでリアルタイム通信をしたいという課題です。
弊社では、今までWebsocketでリアルタイム通信をするとき、node.jsをよく利用していました。
が、すでにあるプログラム群に追加するのはいろいろと面倒だったのです。
そこで、Ratchet WebSockets for PHPなるものがあることがわかりました。
http://socketo.me/
ほほー
これは、私が求めているものに近い!!
しかも、解説が親切!
というわけで、とりあえず、最初のチュートリアルからやってみます。
“hello world”やってみよう、という公式サイトを初心者目線で解説してみます。
http://socketo.me/docs/hello-world
とりあえず、例として、サーバーの下記のパスにratchetを入れてみます。
/var/www/html/test/ratchet/
まず、PSR-0というライブラリとか、Ratchetのライブラリを入手します。
こういうのは、今時はもうcomposerでさくっとやっちゃうのです⊂(^-^)⊃
composerの例文がありますね。
{
"autoload": {
"psr-0": {
"MyApp": "src"
}
},
"require": {
"cboden/ratchet": "0.3.*"
}
}
ちなみに、PSR-0のサイトへ行くと、PSR-4を使ってくれよーん(2016年5月2日現在)と書いてあるので、気を利かしてpsr-4とやっても、ratchetさんのほうで対応していないので、動きません!
上記をテキストファイルに書いて、composer.jsonという名前でサーバーにアップロードします。
$ composer update
とやります。
あとはですね、/var/www/html/test/ratchet/の中に、src/MyAppというディレクトリを作って、その中にChat.phpという名前で次の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();
}
}
次に、/var/www/html/test/ratchet/の中に、binというディレクトリを作って、その中にchat-server.phpという名前で次のPHPファイルを保存します。
<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new Chat(),
8080
);
$server->run();
サーバーで、次のようにやります。
$ php bin/chat-server.php
Windowsで、コマンドプロンプトを立ち上げます。
hogehoge.netというサーバーに上記の設定をしたとすると、
telnet hogehoge.net 8080
とやります。
ちなみに、デフォルトでWindows10にTelnetは無効化されてますので、下記の記事を参考に有効化してください。
Windows10 Telnetを使う
もう一つ、コマンドプロンプトを立ち上げます。
telnet hogehoge.net 8080
とやります。
すると、一方の画面で文字を打つと…
もう一方の画面にでてくるんですね!!
すごい!
感動ひとしお!!!
- aaaaa — bbbbb {2018-01-07 (日) 08:24:57}
