OpenSwoole\WebSocket\Server::__construct()

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

Declaration

<?php OpenSwoole\WebSocket\Server::__construct(string $host, int $port)

Parameters

host

The IP address of the server to listen on

port

The port of the server (root privilege required if the port number is less than 1024)

Return

server

A OpenSwoole\WebSocket\Server object if successful

Description

Create a new WebSocket server. Provide the IP and port you want the server to listen on and OpenSwoole will create a OpenSwoole\WebSocket\Server object for you in return.

The OpenSwoole\WebSocket\Server is a sub-class of OpenSwoole\Server and inherits some features form OpenSwoole\Http\Server as well.

You can use the methods from the OpenSwoole\Server within a WebSocket Server.

Considerations

  • With a WebSocket server you should use OpenSwoole\WebSocket\server->push(...) to send WebSocket data, the OpenSwoole\Server->send(...) method is used for traditional TCP data transmission.

Example

<?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