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

Declaration

<?php
Swoole\WebSocket\Server->on ('handshake', callable $callback)

Parameters

event

The event name

callback

callback function, the callback function returns handshake result status.

Return

success

if success, it returns TRUE, otherwise it returns FALSE.

Description

This function is optional to create a WebSocket server.

The function is executed when a WebSocket connection is established and going into the handshake stage.

The built-in default handshake protocol is Sec-WebSocket-Version: 13. You can override the default handshake protocol by implementing this function.

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('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;
});

$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();