php-fpm模式下與Swoole Websocket服務如何聯絡

php迷途小書童發表於2021-12-20

服務端

<?php
$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
$server->on('open', function (Swoole\WebSocket\Server $server, $request) {
    echo "server: handshake success with fd{$request->fd}\n";
});
$server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($frame->fd, "this is server");
});
$server->on('close', function ($server, $fd) {
    echo "client {$fd} closed\n";
});
$server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
    global $server;//呼叫外部的server
    // $server->connections 遍歷所有websocket連線使用者的fd,給所有使用者推送
    foreach ($server->connections as $fd) {
        // 需要先判斷是否是正確的websocket連線,否則有可能會push失敗
        if ($server->isEstablished($fd)) {
            $server->push($fd, $request->get['message']);
        }
    }
    $response->end('success');
    return;
});
$server->start();

客戶端連線

try {
    $client = new \GuzzleHttp\Client();
    $client->request('GET', 'http://127.0.0.1:9501', ['query' => [
        'message' => '有新品上架了',
    ]]);
} catch (Exception $e) {

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章