OpenSwoole\WebSocket\Server->on('Open', fn)

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

Declaration

<?php OpenSwoole\WebSocket\Server->on('Open', 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 WebSocket connection is established and has completed the Handshake stage.

However, this event is only triggered if you have not implemented your own handshake function, if you have defined your own Handshake event callback, then OpenSwoole won't trigger the Open event as it is up to you to provide this logic. See the Handshake event documentation for more information about this.

You are not required to register this callback event.

Example

The OpenSwoole\Http\Request $request object that is passed to the Open event contains HTTP request data and information about the completed handshake the client went through.

In the Open event callback you can push data back to the client if you need to or even decide to close the connection at this stage.

<?php

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

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

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

$server->on('Open', function(Server $server, OpenSwoole\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();
Last updated on September 1, 2022