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

Declaration

<?php
Swoole\WebSocket\Server->on('Message', 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

This function is executed when a new data Frame is received by the WebSocket Server. The main application logic for the request from the WebSocket client should be defined within this function, this acts as your main application entry point, kind of like a index.php file.

The callback function is passed an object called Swoole\WebSocket\Frame and this contains the data frame information sent by the client.

When the client sends a ping frame, it will not trigger this Message event. The server will automatically return the pong packet back to the client. However, you can process ping requests from the client within the Message event callback if you set 'open_websocket_ping_frame' to true.

It is recommended to read the Frame Object documentation to understand more about how to use it.

This callback is required to be registered when running a WebSocket server

OpCode and Data Types

  • WEBSOCKET_OPCODE_TEXT = 0x1: text data
  • WEBSOCKET_OPCODE_BINARY = 0x2: binary data

Example

If the contents of $frame->data is text, the encoding format will be UTF-8 which is the standard with the WebSocket protocol.

<?php

use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

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

$server->on("Start", function(Server $server)
{
    echo "Swoole WebSocket Server started at 127.0.0.1:9501\n";
});

$server->on('Open', function(Server $server, Swoole\Http\Request $request)
{
    echo "connection open: {$request->fd}\n";

    $server->tick(1000, function() use ($server, $request)
    {
        $server->push($request->fd, json_encode(["hello", time()]));
    });
});

$server->on('Message', function(Server $server, Frame $frame)
{
    echo "received message: {$frame->data}\n";

    $server->push($frame->fd, json_encode(["hello", time()]));
});

$server->on('Close', function(Server $server, int $fd)
{
    echo "connection close: {$fd}\n";
});

$server->start();