OpenSwoole DTLS for PHP

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

Version: OpenSwoole: 4.5.0+

OpenSwoole DTLS Server

DTLS stands for Datagram Transport Layer Security. Simply put, DTLS is UDP + security. OpenSwoole support DTLS from version 4.5.

To enable DTLS at UDP server side, you can use OpenSwoole\Constant::SOCK_UDP | OpenSwoole\Constant::SSL.

Example:

<?php

$server = new OpenSwoole\Server('0.0.0.0', 5000, OpenSwoole\Server::SIMPLE_MODE, OpenSwoole\Constant::SOCK_UDP | OpenSwoole\Constant::SSL);

$server->set([
    'ssl_cert_file' => __DIR__ . '/../ssl/ssl.crt',
    'ssl_key_file' => __DIR__ . '/../ssl/ssl.key',
]);

$server->on('receive', function(OpenSwoole\Server $serv, $fd, $tid, $data) {
    //var_dump($fd, $data, $serv->getClientInfo($fd));
    $serv->send($fd, "echo: $data\n");
});

$server->start();

OpenSwoole DTLS Client

To enable DTLS at UDP client side, you can use OpenSwoole\Constant::SOCK_UDP | OpenSwoole\Constant::SSL.

Example:

<?php
co::run(function() {
    $client = new OpenSwoole\Coroutine\Client(OpenSwoole\Constant::SOCK_UDP | OpenSwoole\Constant::SSL);
    if (!$client->connect('127.0.0.1', 5000)) {
        exit("connect failed\n");
    }
    $client->send("hello world");
});
Last updated on September 20, 2022