Coroutine TCP/UDP Client

Coroutine TCP/UDP client.

Instead of using the Coroutine Socket API, You can use the Swoole Coroutine Client API.

Methods

  • Swoole\Coroutine\Client->__construct
  • Swoole\Coroutine\Client->set
  • Swoole\Coroutine\Client->connect
  • Swoole\Coroutine\Client->send
  • Swoole\Coroutine\Client->recv
  • Swoole\Coroutine\Client->close
  • Swoole\Coroutine\Client->sendfile
  • Swoole\Coroutine\Client->sendto
  • Swoole\Coroutine\Client->isConnected
  • Swoole\Coroutine\Client->getsockname
  • Swoole\Coroutine\Client->getpeername

    Example:

    <?php
    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
    if (!$client->connect('127.0.0.1', 9501, 0.5))
    {
        exit("connect failed. Error: {$client->errCode}\n");
    }
    $client->send("hello world\n");
    echo $client->recv();
    $client->close();
    

    Settings:

    The following settings are supported by the client to help with the protocol parsing.

    <?php
    
    [   
        'timeout' => 0.5,
        'connect_timeout' => 1.0,
        'write_timeout' => 10.0,
        'read_timeout' => 0.5,
        'open_length_check'     => 1,
        'package_length_type'   => 'N',
        'package_length_offset' => 0, 
        'package_body_offset'   => 4, 
        'package_max_length'    => 2000000,
    ]
    

    Other settings

    <?php
    
    // Check EOF
    $client->set(array(
        'open_eof_check' => true, // if check the EOF
        'package_eof' => "\r\n\r\n", // EOF
        'package_max_length' => 1024 * 1024 * 2,
    ));
    
    // Check package length
    $client->set(array(
        'open_length_check'     => 1,
        'package_length_type'   => 'N',
        'package_length_offset' => 0,       // The offset of package length variable
        'package_body_offset'   => 4,       // The offset of body of the package
        'package_max_length'    => 2000000,  // The max length of the package
    ));
    
    // Set the socket buffer size
    $client->set(array(
        'socket_buffer_size'     => 1024*1024*2, // 2MB buffer size
    ));
    
    // Turn off the Nagle TCP algorithm
    $client->set(array(
        'open_tcp_nodelay'     =>  true,
    ));
    
    // Setup SSL files
    $client->set(array(
        'ssl_cert_file'     =>  $your_ssl_cert_file_path,
        'ssl_key_file'     =>  $your_ssl_key_file_path,
        'ssl_allow_self_signed' => TRUE,
        'ssl_verify_peer' => TRUE,
        'ssl_cafile' => TRUE,
        'ssl_host_name' => $ssl_host_name,
        'verify_peer' => TRUE,
        'verify_peer_name' => TRUE,
    ));
    
    // Setup local TCP address
    $client->set(array(
        'bind_address'     =>  '192.168.1.100',
        'bind_port'     =>  36002,
    ));
    
    // Setup socks5 proxy
    $client->set(array(
        'socks5_host'     =>  '192.168.1.100',
        'socks5_port'     =>  1080,
        'socks5_username' => 'username',
        'socks5_password' => 'password',
    ));