OpenSwoole Client Configuration

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

Declaration

<?php OpenSwoole\Coroutine\<type>\Client->set(array $settings): bool

Parameters

settings

A key-value array of settings

Return

Returns true if successful and false when not


Description

Update the settings of a TCP/UDP Client before using it.

Important

The configuration options on this page are for the following clients, they share the same options:

See each specific client documentation for additional settings per client.


Default settings and Configuration

If there is no explicit settings updated, the clients uses the following default values.

Lowercase Header

Add support for lowercase header style.

<?php
$client->set([
    'lowercase_header' => false,
]);

Protocol Analysis

The following settings are supported by the client to help with the protocol parsing, this also helps with TCP packet boundary issues.

End Character Detection

<?php
$client->set([

    // Check for EOF
    'open_eof_check' => true,

    // EOF packet to look for
    'package_eof' => "\r\n\r\n",
    'package_max_length' => 1024 * 1024 * 2,
]);

Packet Length Detection

<?php
$client->set([
    'open_length_check' => true,
    'package_length_type' => 'N',

    // Nth byte for the value of the packet length
    'package_length_offset' => 0,

    // After Nth bytes, start to calculate the length
    'package_body_offset' => 4,

    // Maximum protocol length
    'package_max_length' => 2000000,
]);

The client supports both open_length_check and open_eof_check, 2 forms of automatic protocol processing. When using these automatic protocol parsing features, the recv() function will not accept any length parameters because the client has been configured to read a complete packet.

MQTT Protocol Parsing

<?php
$client->set([
    'open_mqtt_protocol' => true,
]);

Enable MQTT protocol parsing and analysis, when set the receive callback will be given a complete MQTT packet.

Socket Buffer Size

<?php
$client->set([
    // 2M buffer area
    'socket_buffer_size' => 1024 * 1024 * 2,
]);

Set the operating system cache when using sockets, the client will use this buffer when receiving data as a memory buffer.

Turn off Nagle Merge Algorithm

<?php
$client->set([
    'open_tcp_nodelay' => true,
]);

Disables the Nagle Algorithm when using TCP/IP, when not disabled it helps reduce the number of packets sent over a network and improves efficiency, however, sometimes its characteristics are not desired and if you want a free-flow of data through a network, you may want to disable this.


SSL Client Configuration

SSL/TLS Certificate

<?php
$client->set([
    'ssl_cert_file' => $your_ssl_cert_file_path,
    'ssl_key_file' => $your_ssl_key_file_path,
]);

SSL Verify Peer

<?php
$client->set([
    'ssl_verify_peer' => true,
]);

When this setting is enabled, it will verify whether the certificate corresponds to the host domain name, if it is not, the connection will be automatically closed.

Self-signed Certificates

<?php
$client->set([
    'ssl_verify_peer' => true,
    'ssl_allow_self_signed' => true,
]);

You can give self-singed SSL certificates approval.

SSL Host Name

<?php
$client->set([
    'ssl_host_name' => 'openswoole.com',
]);

Setting the server host name, and ssl_verify_peer the configuration is used in conjunction with or Client->verifyPeerCert.

SSL Cafile

<?php
$client->set([
    'ssl_cafile' => '/etc/ssl/ca',
]);

When ssl_verify_peer is set to true, the certificate used to verify the distal end of the CA certificate is set using this option. This option is a CA certificate full path and file name on the local file system.

SSL Passphrase

<?php
$client->set([
    'ssl_passphrase' => '********',
]);

The password used for the local filesystem SSL certificate that is set with ssl_cert_file.

For example:

<?php
$client = new OpenSwoole\Client(OpenSwoole\Constant::SOCK_TCP | Swoole\Constant::SSL);

$client->set([
    'ssl_cert_file' => __DIR__.'/ca/client-cert.pem',
    'ssl_key_file' => __DIR__.'/ca/client-key.pem',
    'ssl_allow_self_signed' => true,
    'ssl_verify_peer' => true,
    'ssl_cafile' => __DIR__.'/ca/ca-cert.pem',
    'ssl_passphrase' => '********',
]);

if(!$client->connect('127.0.0.1', 9501, -1))
{
    exit("Connection failed: {$client->errCode}\n");
}

echo "Connection OK\n";

$client->send("Hello World! " . str_repeat('A', $i) . "\n");

echo $client->recv();

Package Length Configuration

The length function must return an integer.

Just like the OpenSwoole\Server, the configuration option package_length_func is also available to use with the TCP/UDP client. It works exactly the same way and is used in conjunction with open_length_check.

To learn more we shall look at a example:

First of all, the function must return an integer.

  • Return 0, means insufficient data, need to receive more data
  • Return -1, means the data is wrong, the connection will be automatically closed
  • Return as an integer the total length of the package (including the total length of the header and the body),the client will then automatically put the package together and return it to the callback function

The default maximum read is 8K of data, if the header length is less likely to be copied in memory, package_body_offset can be set and the client will only read the header length.

<?php

$client = new OpenSwoole\Client(OpenSwoole\Constant::SOCK_TCP);

$client->set([
    'open_length_check' => true,
    'package_length_func' => function($data)
    {
        if(strlen($data) < 8)
        {
            return 0;
        }

        $length = intval(trim(substr($data, 0, 8)));

        if($length <= 0)
        {
            return -1;
        }

        return $length + 8;
    },
]);

if(!$client->connect('127.0.0.1', 9501, -1))
{
    exit("connect failed. Error: {$client->errCode}\n");
}

$client->send("Hello World!\n");

echo $client->recv();
$client->close();

Socks5 Proxy

You can configure a Socks5 proxy connection.

<?php

$client->set([
    'socks5_host' => '192.168.1.100',
    'socks5_port' => 1080,
    'socks5_username' => 'username',
    'socks5_password' => 'password123',
));

HTTP Proxy

You can configure a HTTP proxy connection.

Both http_proxy_port and http_proxy_password cannot be null.

Basic Setup

<?php

$client->set([
    'http_proxy_host' => '192.168.1.102',
    'http_proxy_port' => 1080,
]);

HTTP Proxy Credentials

<?php

$client->set([
    'http_proxy_user' => 'username',
    'http_proxy_password' => 'password123',
]);

HTTP2 settings

<?php
$client->set([
    'http2_header_table_size' => 4095,
    'http2_initial_window_size' => 65534,
    'http2_max_concurrent_streams' => 1281,
    'http2_max_frame_size' => 16383,
    'http2_max_header_list_size' => 4095,
]);

Bind Address

Under some hardware or even virtual configurations, some servers have access to multiple network cards. This means you might want to specify which network address to use. You can bind a client to a specific IP or socket. You must set both the address and port.

<?php

$client->set([
    'bind_address' => '192.168.1.100',
    'bind_port' => 36002,

    // Or

    'bind_address' => current(swoole_get_local_ip()),
    'bind_port' => -1,
]);

Example and Usage

<?php
use OpenSwoole\Coroutine\Client;

co::run(function()
{
    $client = new Client(OpenSwoole\Constant::SOCK_TCP);

    // Configure your client before using it
    $client->set([
        'open_eof_check' => true,
        'package_eof' => "\r\n\r\n",
        'package_max_length' => 1024 * 1024 * 2,
    ]);

    if(!$client->connect('127.0.0.1', 9501, 0.5))
    {
        exit("Connection failed: {$client->errCode}\n");
    }

    $client->send("Hello World!\n");

    echo $client->recv();

    $client->close();
});

Note: The above code example is for the Coroutine TCP/UDP client, consider this when using the OpenSwoole clients, you may want a different protocol client; HTTP or HTTP2.

Last updated on September 20, 2022