Swoole\WebSocket\Server->on('Request', fn)

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


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\WebSocket\Server->on('Request', callable $callback)

Parameters

event

The event name to set a callback for

callback

Callable function for the server event type

Return

If success, it returns true, otherwise it returns false

Description

The WebSocket server inherits the Swoole\Http\Server object and gains access to the HTTP server API and features. To learn more it is suggested to read the Swoole HTTP Server documentation.

The Request event is usually part of the HTTP Server class but it can also be used within a WebSocket server. By setting the Request event, Swoole will trigger the callback to handle HTTP protocol requests. It is like running a WebSocket and HTTP server at the same time.

If you do not register the Request event with a WebSocket server, any HTTP request will result in a 400 response given to the client.

You may also use the HTTP server configuration when running a WebSocket server.

You are not required to register this callback event

Example

Even though we get access to the Request event within a WebSocket server, sending data back to the client is a little different, so let's take a look at some examples.

Process-oriented Code

Inside a normal server.php file, we can start up a WebSocket server which responds to HTTP requests and broadcasts back to all clients who are connected.

<?php

$server = new Swoole\WebSocket\Server("127.0.0.1", 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(Swoole\WebSocket\Server $server, $fd)
{
    echo "client {$fd} closed\n";
});

// The Request event closure callback is passed the context of $server
$server->on('Request', function(Swoole\Http\Request $request, Swoole\Http\Response $response) use ($server)
{
    /*
     * Loop through all the WebSocket connections to
     * send back a response to all clients. Broadcast
     * a message back to every WebSocket client.
     */
    foreach($server->connections as $fd)
    {
        // Validate a correct WebSocket connection otherwise a push may fail
        if($server->isEstablished($fd))
        {
            $server->push($fd, $request->get['message']);
        }
    }
});

$server->start();

Object-oriented Code

In this example we can use a PHP object to store our web server and access the main $server to send back data to the connected users, broadcasting back to all WebSocket clients.

<?php

class WebSocketServerTest
{
    public $server;

    public function __construct()
    {
        $this->server = new Swoole\WebSocket\Server("127.0.0.1", 9501);

        $this->server->on('Open', function(Swoole\WebSocket\Server $server, $request)
        {
            echo "server: handshake success with fd{$request->fd}\n";
        });

        $this->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");
        });

        $this->server->on('Close', function(Swoole\WebSocket\Server $server, $fd)
        {
            echo "client {$fd} closed\n";
        });

        // The Request event closure callback is passed the context of $server
        $this->server->on('Request', function(Swoole\Http\Request $request, Swoole\Http\Response $response)
        {
            /*
            * Loop through all the WebSocket connections to
            * send back a response to all clients. Broadcast
            * a message back to every WebSocket client.
            */
            foreach($this->server->connections as $fd)
            {
                // Validate a correct WebSocket connection otherwise a push may fail
                if($this->server->isEstablished($fd))
                {
                    $this->server->push($fd, $request->get['message']);
                }
            }
        });
    }

    public function start()
    {
        $this->server->start();
    }

    // ...
}

// Create a new WebSocket server instance
$webSocketServer = new WebSocketServerTest();

// Start the server
$webSocketServer->start();
Last updated on August 31, 2022