OpenSwoole\Coroutine\Client->connect(...)

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

Declaration

<?php OpenSwoole\Coroutine\Client->connect(string $host, int $port, float $timeout = 0.5): bool

Parameters

host

Host name or IP of the remote server to connect to, OpenSwoole will automatically resolve a domain name

port

Port of the remote server to connect to

timeout

The timeout (in seconds ms) of connect/send/recv, the default value is 0.5 seconds

Return

Returns false if the connection failed, check the error code to see why


Description

Establish a new connection to a server.

If the set $timeout is reached, the client will automatically close the connection. If the connection fails it will return false, a timeout will result in an error code of 110, use $client->errCode to check.


Failed Connections

Once a connection attempt fails, you cannot directly reconnect again, first, you must close the connection and then try to connect again. For example:

<?php

// Check if connection has failed
if($client->connect('127.0.0.1', 9501) == false)
{
    // Close existing socket
    $client->close();

    // Now it is valid to try again
    $client->connect('127.0.0.1', 9501);
}

...

Or another way of handling failed connections:

<?php

// Connection is either true or false
if($client->connect('127.0.0.1', 9501))
{
    $client->send('data');
}
else
{
    echo "Connection failed.\n " . $client->errCode;
}

// Using a socket instead...
if($client->connect('/tmp/rpc.sock'))
{
    $client->send('data');
}
else
{
    echo "Connection failed.\n " . $client->errCode;
}

...

Example

<?php

$client = new OpenSwoole\Coroutine\Client(OpenSwoole\Constant::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();
Last updated on September 20, 2022