LoginSignup
3
3

More than 5 years have passed since last update.

phpのratchet/pawlを使ってwebsocket clientを作る

Last updated at Posted at 2019-03-12

とあるAPIサービスのクライアントサンプルがtextalk/websocketで書かれていたのですが、
なんかメモリリーク起こしているようで、立ち上げっぱなしにしてると落ちるため、
ratchet/pawlを使って書き直しました。

composerでratchet/pawlをインストール

composer require ratchet/pawl

コード

client.php
<?php

require __DIR__ . '/vendor/autoload.php';

/**
 * 接続
 */
function connectServer($connector, $loop) {
    // 接続先情報(適宜変更)
    $url = "ws://localhost:8080";
    $connector($url)->then(function(Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
        // メッセージ受信イベント
        $conn->on("message", function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) {
            // メッセージ受け取ったときの処理(適宜変更)
            print_r($msg);
        });

        // 切断イベント
        $conn->on("close", function($code = null, $reason = null) use ($connector, $loop) {
            $loop->addTimer(1, function() use ($connector, $loop) {
                // 切断されたら自動で再接続させる
                connectServer($connector, $loop);
            });
        });

        // 接続できたらテストでサーバへメッセージ送ってみる (適宜変更)
        sendMessage($conn, "hello world.");
    }, function (\Exception $e) use ($loop) {
        // 例外処理(処理停止)
        $loop->stop();
    });
}


/**
 * メッセージ送信
 */
function sendMessage($conn, $msg) {
    $conn->send($msg);
}


/**
 * 本体
 */
$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);
connectServer($connector, $loop);
$loop->run();
3
3
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
3
3