WebSocket Ping Pong

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

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 OpenSwoole will automatically response to ping/pong events for you.

Example

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

OpenSwoole Server

<?php

use OpenSwoole\WebSocket\Frame;
use OpenSwoole\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 OpenSwoole!');
});

$server->start();

OpenSwoole Client

<?php

use OpenSwoole\WebSocket\Frame;
use OpenSwoole\Coroutine\Http\Client;

co::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 September 1, 2022