WebSocket Ping Pong

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Description

A WebSocket server is an application which maintains long-lived connections with clients, because there can be long periods with no communication between requests, the connection may be disconnected. To help keep WebSocket connections alive for long periods we can use Ping and Pong frames. This can be thought of as a heartbeat mechanism, the client will send a ping frame to the server and in response the server will pong back to the client, maintaining that connection over a long time. Otherwise, if the ping/pong fails either party knows to disconnect the client.

For this to work where you can manage ping/pong requests manually, you must checkout the documentation for open_websocket_ping_frame and open_websocket_pong_frame, otherwise Swoole will automatically response to ping/pong events for you.

Example

Below are two examples for how you can implement ping/pong events in Swoole, one example is for a Swoole server and the other is for the Swoole client.

Swoole Server

<?php

use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

$server = new Server('127.0.0.1', 9501);

$server->on('Message', function(Server $server, Frame $frame)
{
    // Check for a ping event using the OpCode
    if($frame->opcode === WEBSOCKET_OPCODE_PING)
    {
        $pongFrame = new Frame;

        // Setup a new data frame to send back a pong to the client
        $pongFrame->opcode = WEBSOCKET_OPCODE_PONG;
        $server->push($frame->fd, $pongFrame);
    }

    $server->push($frame->fd, 'Hello, from Swoole!');
});

$server->start();

Swoole Client

<?php

use Swoole\WebSocket\Frame;
use Swoole\Coroutine\Http\Client;
use function Swoole\Coroutine\run;

run(function()
{
    $cli = new Client('127.0.0.1', 9501);

    $cli->upgrade('/');

    $pingFrame = new Frame;
    $pingFrame->opcode = WEBSOCKET_OPCODE_PING;

    // Send a PING
    $cli->push($pingFrame);

    // Receive a PONG
    $pongFrame = $cli->recv();
    var_dump($pongFrame->opcode === WEBSOCKET_OPCODE_PONG);
});
Last updated on August 31, 2022