Swoole Client

Methods list:

public Swoole\Client::__construct ( int $sock_type [, integer $is_async ] )

Alias: public swoole_client::__construct ( int $sock_type [, integer $is_async ] )

Create Swoole sync or async TCP/UDP client, with or without SSL.

Compile swoole with enable-openssl or with-openssl-dir to support SSL. Also add SWOOLE_SSL to the constructor parameter of class swoole_client.

<?php
$client = new Swoole\Client(SWOOLE_TCP | SWOOLE_ASYNC | SWOOLE_SSL);

or

<?php
swoole_client->__construct(int $sock_type, int $is_sync = SWOOLE_SOCK_SYNC, string $key);
  • $sock_type the type of socket
  • $is_sync set the client to be synchronous or asynchronous
  • $key the key used for long connection, the default key is IP:PORT. the connection which has the same key will be reused

Return

Swoole\Client object

Example

Create persistent TCP connection in php-fpm or apache php:

<?php
$cli = new swoole_client(SWOOLE_TCP | SWOOLE_KEEP);

public bool Swoole\Client::connect ( string $host [, integer $port [, integer $timeout [, integer $flag ]]] )

Alias: public bool swoole_client::connect ( string $host [, integer $port [, integer $timeout [, integer $flag ]]] )

Connect to the remote TCP/UDP port.

<?php
bool swoole_client->connect(string $host, int $port, float $timeout = 0.1, int $flag = 0)
  • $host the ip address the client connects to
  • $port the port the client connects to
  • $timeout the timeout(second) of connect/send/recv, the dafault value is 0.1s
  • $flag if the type of client is UDP, the $flag means if to enable the configuration udp_connect. If the configuration udp_connect is enabled, the client will only receive the data from specified ip:port. If the type of client is TCP and the $flag is setted to 1, it must use swoole_client_select to check the connection status before send/recv.

$timeout is noneffective for asynchronous client.

Synchronous mode

This method won't return until the client connects to the server successfully or unsuccessfully.

<?php
if ($cli->connect('127.0.0.1', 9501)) {
    $cli->send("data");
} else {
    echo "connect failed.";
}

Asynchronous mode

<?php
if ($cli->connect('127.0.0.1', 9501)) {
      $cli->send("data");
} else {
      echo "connect failed.";
}

public bool Swoole\Client::close ([ bool $force ] )

Alias: public bool swoole_client::close ([ bool $force ] )

Close the connection.

<?php
bool $swoole_client->close(bool $force = false);
  • $force if close the connection forcibly

Return

bool

public void Swoole\Client::enableSSL(mixed $var)

Alias: swoole_client::enableSSL(mixed $var)

<?php
bool swoole_client->enableSSL(mixed $var);

If the client hasn't enabled the SSL in the construction and has connnected to the server, you can enable the SSL for the TCP client by this method.

Parameter

For sync TCP client, it should not pass parameter to this method and this method wouldn't return until the process of enabling SSL finished.

For async TCP client, it should pass the callback function which is called after the process of enabling SSL finished.

Return

bool

Example

Sync TCP client with SSL:

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

if ($client->enableSSL())
{
    $client->send("hello world\n");
    echo $client->recv();
}
$client->close();

Async TCP client with SSL:

<?php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function(swoole_client $cli) {
    $cli->send("hello world\n");
});
$client->on("receive", function(swoole_client $cli, $data) {
    echo "Receive: $data";
    $cli->send(str_repeat('A', 10)."\n");

    $cli->enableSSL(function($client) { 
        $client->send("hello");
    })
});
$client->on("error", function(swoole_client $cli){
    echo "error\n";
});
$client->on("close", function(swoole_client $cli){
    echo "Connection close\n";
});
$client->connect('127.0.0.1', 9501);

public string Swoole\Client::getPeerCert()

Alias: swoole_client->getPeerCert()

<?php
string swoole_client->getPeerCert();

Get the Cert of the remote server.

It needs the support of openssl. You should compile swoole with --enable-openssl.

Return

The Cert of the remote server. You can use the function openssl_x509_parse of extension openssl to parse the cert information.

public array Swoole\Client::getPeerName()

Alias: swoole_client->getPeerName()

<?php
array swoole_client->getPeerName();

Get the remote socket name of the connection.

Return

The array of remote socket host and port

<?php
array('host' => '127.0.0.1', 'port' => 53652)

public array Swoole\Client::getSocket()

Alias: swoole_client::getSocket()

<?php
resource swoole_client->getSocket()

Get the TCP socket of the connection.

This method needs the support of extension sockets. You should compile swoole with --enable-sockets.

Return

A resource which holds the handle of socket

Example

<?php
$socket = $client->getSocket();
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

public array Swoole\Client::getSockName()

Alias: swoole_client::getSockName()

<?php
array swoole_client->getSockName();

Get the local socket name of the connection.

Return

The array of local socket host and port

<?php
array('host' => '127.0.0.1', 'port' => 53652)

public boolean Swoole\Client::isConnected()

Alias: swoole_client::isConnected()

<?php
bool swoole_client->isConnected()

Check if the connection is established.

The method returns the connection status of application layer. Perhaps the return means that the client is connected to the server, but the connection is unusable.

Return

bool

public integer Swoole\Client::on(string $event, callable $callback)

Alias: swoole_client::on(string $event, mixed $callback)

<?php
int swoole_client::on(string $event, mixed $callback)

Only can be used in async mode.

Set the callback functions for the events:

  • connect
  • receive
  • close
  • error
  • BufferFull
  • BufferEmpty

connect/close events will be emitted immediately when UDP client is created or closed.

Parameter

  • $event the event to be registered with callback function
  • $callback the callback function

Example

<?php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function(swoole_client $cli) {
    $cli->send("GET / HTTP/1.1\r\n\r\n");
});
$client->on("receive", function(swoole_client $cli, $data){
    echo "Receive: $data";
    $cli->send(str_repeat('A', 100)."\n");
    sleep(1);
});
$client->on("error", function(swoole_client $cli){
    echo "error\n";
});
$client->on("close", function(swoole_client $cli){
    echo "Connection close\n";
});
$client->connect('127.0.0.1', 9501);

public string Swoole\Client::recv(int $size = 65535, int $flags = 0)

Alias: swoole_client::recv(int $size = 65535, int $flags = 0)

<?php
string swoole_client->recv(int $size = 65535, int $flags = 0);

Receive data from the remote socket.

Parameter

  • $size the buffer size of receiving data

  • $flags the configuration of receiving data(Check the predefined constants of class swoole_client)

If the swoole client has setted the configuration about check of EOF/Length, it doesn't need to set the parameter $size and $flags and the swoole client will return the whole package.

Return

If the client receives data successfully, it returns the length of data received. Or it returns false and sets $swoole_client->errCode.

Example

$client->recv(8192, swoole_client::MSG_PEEK | swoole_client::MSG_WAITALL);

public integer Swoole\Client::send(string $data)

Alias: swoole_client::send(string $data)

<?php
int swoole_client->send(string $data);

Send data to the remote TCP socket.

Parameter

  • $data the data to send which can be text or binary

Return

If the client sends data successfully, it returns the length of data sent. Or it returns false and sets $swoole_client->errCode.

For sync client, there is no limit for the data to send.

For async client, The limit for the data to send is socket_buffer_size.

public boolean Swoole\Client::sendfile(string $filename, int $offset = 0, int $length = 0)

Alias: swoole_client->sendfile(string $filename, int $offset = 0, int $length = 0)

<?php
bool swoole_client->sendfile(string $filename, int $offset = 0, int $length = 0)

Send file to the remote TCP socket.

This is a wrapper of the Linux sendfile system call.

Parameter

  • $filename the path of file to send

  • $offset the offset of file to start send

  • $length the length of file to send. The default value is the whole length of file.

Return

bool

If the file doesn't exist, the return is false.

public boolean Swoole\Client::sendto(string $ip, int $port, string $data)

Alias: swoole_client::sendto(string $ip, int $port, string $data)

<?php
bool swoole_client->sendto(string $ip, int $port, string $data)

Send data to the remote UDP address. The swoole client should be type of SWOOLE_SOCK_UDP or SWOOLE_SOCK_UDP6.

Parameter

  • $ip the ip address of remote host, ipv4 or ipv6

  • $port the port number of remote host

  • $data the data to send which should be less-than 64K.

Return

bool

public void Swoole\Client::set(array $setting)

Alias: swoole_client::set(array $setting)

<?php
swoole_client->set(array $setting)

Set the Swoole client parameters before the connection is established.

Parameter

  • $setting the setting of swoole client

Example

<?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,
));

// 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',
));

public void Swoole\Client::sleep()

Alias: swoole_client::sleep()

<?php
swoole_client->sleep();

Remove the TCP client from Event Loop.

Example

<?php
$client->on("receive", function(swoole_client $cli, $data){
    //sleep mode and stop receive data
    $cli->sleep();
    swoole_timer_after(5000, function() use ($cli) {
        // wakeup the client and start to receive data
        $cli->wakeup();
    });
});

Swoole\Client::wakeup()

Alias: swoole_client::wakeup()

<?php
swoole_client->wakeup();

Add the TCP client into the system event loop.

Example

<?php
$client->on("receive", function(swoole_client $cli, $data){
    //sleep mode and stop receive data
    $cli->sleep();
    swoole_timer_after(5000, function() use ($cli) {
        // wakeup the client and start to receive data
        $cli->wakeup();
    });
});