WebSocket Server

We can create a high performance WebSocket Server with PHP Swoole. The WebSocket Server mantains a persistent connection with each client and sends messages to clients when the connection is established.

You can use the methods of Swoole\Server within a WebSocket Server.

Methods

  • Swoole\WebSocket\Server::__construct
  • Swoole\WebSocket\Server->start
  • Swoole\WebSocket\Server->on
  • Swoole\WebSocket\Server->push
  • Swoole\WebSocket\Server->exist
  • Swoole\WebSocket\Server->isEstablished
  • Swoole\WebSocket\Server->pack
  • Swoole\WebSocket\Server->unpack
  • Swoole\WebSocket\Server->disconnect
  • Swoole\WebSocket\Server->getClientInfo

    Events

  • Swoole\WebSocket\Server->on('start', fn)
  • Swoole\WebSocket\Server->on('open, fn)
  • Swoole\WebSocket\Server->on('handshake, fn)
  • Swoole\WebSocket\Server->on('message, fn)
  • Swoole\WebSocket\Server->on('close, fn)

    Classes

  • Swoole\WebSocket\Frame
  • Swoole\WebSocket\CloseFrame

    Example

    <?php
    
    use Swoole\WebSocket\Server;
    use Swoole\Http\Request;
    use Swoole\WebSocket\Frame;
    
    $server = new Server("0.0.0.0", 9502);
    
    $server->on("start", function (Server $server) {
        echo "Swoole WebSocket Server is started at http://127.0.0.1:9502\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();