__construct Method

void AsyncTcpConnection::__construct(string $remote_address, $context_option = null)

Creates an asynchronous connection object.

AsyncTcpConnection allows Workerman to initiate asynchronous connections as a client to a remote server, and to asynchronously send and handle data on the connection via the send interface and onMessage callback.

Parameters

Parameter:remote_address

The address to connect to, for example:
tcp://www.baidu.com:80
ssl://www.baidu.com:443
ws://echo.websocket.org:80
frame://192.168.1.1:8080
text://192.168.1.1:8080

Parameter:$context_option

This parameter requires (workerman >= 3.3.5)

Used to set the socket context, such as using bindto to set which (network card) IP and port to access the external network, set SSL certificates, etc.

Refer to stream_context_create, Socket Context Options, SSL Context Options

Note

Currently, the supported protocols by AsyncTcpConnection include tcp, ssl, ws, frame, text.

Custom protocols are also supported, see How to customize protocols.

Among them, ssl requires Workerman >= 3.3.4 and the openssl extension to be installed.

As of now, AsyncTcpConnection does not support the http protocol.

You can use new AsyncTcpConnection('ws://...') to initiate a websocket connection to a remote websocket server in Workerman, just like a browser, see example. However, you cannot initiate a websocket connection in Workerman using the form new AsyncTcpConnection('websocket://...').

Example

Example 1: Asynchronous Access to External HTTP Service

use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$task = new Worker();
// Asynchronously establish a connection object to www.baidu.com when the process starts, and send data to retrieve data
$task->onWorkerStart = function($task)
{
    // The HTTP protocol cannot be specified directly, but you can simulate HTTP protocol data sending using TCP
    $connection_to_baidu = new AsyncTcpConnection('tcp://www.baidu.com:80');
    // When the connection is successfully established, send the HTTP request data
    $connection_to_baidu->onConnect = function(AsyncTcpConnection $connection_to_baidu)
    {
        echo "connect success\n";
        $connection_to_baidu->send("GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: keep-alive\r\n\r\n");
    };
    $connection_to_baidu->onMessage = function(AsyncTcpConnection $connection_to_baidu, $http_buffer)
    {
        echo $http_buffer;
    };
    $connection_to_baidu->onClose = function(AsyncTcpConnection $connection_to_baidu)
    {
        echo "connection closed\n";
    };
    $connection_to_baidu->onError = function(AsyncTcpConnection $connection_to_baidu, $code, $msg)
    {
        echo "Error code:$code msg:$msg\n";
    };
    $connection_to_baidu->connect();
};

// Run worker
Worker::runAll();

Example 2: Asynchronous Access to External WebSocket Service, with Local IP and Port for Access

<?php
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker();

$worker->onWorkerStart = function($worker) {
    // If you want to initiate a connection in only one process, you can do so by checking $worker->id, for example, only initiating a connection in process 0
    if ($worker->id != 0) {
        return;
    }
    // Set the local IP and port to access the other host (each socket connection will occupy a local port)
    $context_option = array(
        'socket' => array(
            // The IP must be the local network card IP and must be able to access the other host, otherwise it is invalid
            'bindto' => '114.215.84.87:2333',
        ),
    );

    $con = new AsyncTcpConnection('ws://echo.websocket.org:80', $context_option);

    $con->onConnect = function(AsyncTcpConnection $con) {
        $con->send('hello');
    };

    $con->onMessage = function(AsyncTcpConnection $con, $data) {
        echo $data;
    };

    $con->connect();
};

Worker::runAll();

Example 3: Asynchronous Access to External WSS Port, with Local SSL Certificate Set

<?php
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker();

$worker->onWorkerStart = function($worker){
    // Set the local IP and port to access the other host as well as the SSL certificate
    $context_option = array(
        'socket' => array(
            // The IP must be the local network card IP and must be able to access the other host, otherwise it is invalid
            'bindto' => '114.215.84.87:2333',
        ),
        // SSL options, refer to https://php.net/manual/zh/context.ssl.php
        'ssl' => array(
            // The local certificate path. Must be in PEM format, containing both the local certificate and private key.
            'local_cert'        => '/your/path/to/pemfile',
            // The password for the local_cert file.
            'passphrase'        => 'your_pem_passphrase',
            // Whether to allow self-signed certificates.
            'allow_self_signed' => true,
            // Whether to verify the SSL certificate.
            'verify_peer'       => false
        )
    );

    // Initiate an asynchronous connection
    $con = new AsyncTcpConnection('ws://echo.websocket.org:443', $context_option);

    // Set to use SSL encryption
    $con->transport = 'ssl';

    $con->onConnect = function(AsyncTcpConnection $con) {
        $con->send('hello');
    };

    $con->onMessage = function(AsyncTcpConnection $con, $data) {
        echo $data;
    };

    $con->connect();
};

Worker::runAll();