Swoole WebSocket server

The following PHP codes shows how to write a simple WebSocket server. The WebSocket server sends the client a message when the WebSocket connection is established.

The swoole_websocket_server class inherits from the class swoole_server.

Example Code

<?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 message is from swoole websocket server.");
});

$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});

$server->start();

Events and Callback Functions

The class swoole_websocket_server inherits from the class swoole_server. It adds three new events excpet for the event of class swoole_server and class swoole_http_server.

onHandShake

This event happens when the websocket connection start the handshake process. The swoole_websocket_server has built-in callback function registered for event handshake. But you can also choose to custom your callback function for event handshake.

Example

<?php
function onHandShake(swoole_http_request $request, swoole_http_response $response)

The callback function for event handshake is optional.

If the callback function for event handshake has been customed, the event open would not be triggered.

The built-in protocol of handshake is Sec-WebSocket-Version: 13, it needs to implemen t the process of handshake when the browser is in low-version.

Example Code

<?php
$server->on('handshake', function (\swoole_http_request $request, \swoole_http_response $response) {
    $secWebSocketKey = $request->header['sec-websocket-key'];
    $patten = '#^[+/0-9A-Za-z]{21}[AQgw]==$#';

    if (0 === preg_match($patten, $secWebSocketKey) || 16 !== strlen(base64_decode($secWebSocketKey))) {
        $response->end();
        return false;
    }

    echo $request->header['sec-websocket-key'];

    $key = base64_encode(sha1($request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));

    $headers = [
        'Upgrade' => 'websocket',
        'Connection' => 'Upgrade',
        'Sec-WebSocket-Accept' => $key,
        'Sec-WebSocket-Version' => '13',
    ];

    // WebSocket connection to 'ws://127.0.0.1:9502/'
    // failed: Error during WebSocket handshake:
    // Response must not include 'Sec-WebSocket-Protocol' header if not present in request: websocket
    if (isset($request->header['sec-websocket-protocol'])) {
        $headers['Sec-WebSocket-Protocol'] = $request->header['sec-websocket-protocol'];
    }

    foreach ($headers as $key => $val) {
        $response->header($key, $val);
    }

    $response->status(101);
    $response->end();
    echo "connected!" . PHP_EOL;
    return true;
});

onOpen

The event open happens when the websocket server and client has created the connection and finished the handshake. And the callback function registered for event open will be called.

Example

<?php
function onOpen(swoole_websocket_server $svr, swoole_http_request $req)

In the callback function for event open, you can push message to client and close the connection.

The callback function for event open is optional.

Events and Callback Functions

onMessage

The event message happens when the swoole websocket server receives the data frame from the client.

Example

<?php
function onMessage(swoole_server $server, swoole_websocket_frame $frame)

For swoole websocket server, it must set the callback function for the event message

The ping frame from the client will not trigger the event message and the swoole websocket server will respond pong automatically.

swoole_websocket_frame

The class swoole_websocket_frame has four properties:

OpCode and Data type

Method

The swoole_websocket_server class inherits from the class swoole_server. It has also its own method.

swoole_websocket_server->push

This method is to push the message to the client. The max length of message is 2M.

<?php
bool swoole_websocket_server->push(int $fd, string $data, int $opcode = 1, bool $finish = true);

Predefined Contants

Types of websocket data frame

Status of websocket connection

If the swoole_websocket_server has been setted the callback function of event request, it can be used as Http server.

If the swoole_websocket_server hasn't been setted the callback function of event request and received http request, it would repond http 400 error.