Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Coroutine\Client->connect(string $host, int $port, float $timeout = 0.5): bool
Host name or IP of the remote server to connect to, OpenSwoole will automatically resolve a domain name
Port of the remote server to connect to
The timeout (in seconds ms) of connect/send/recv, the default value is 0.5 seconds
Returns false
if the connection failed, check the error code to see why
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.
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;
}
...
<?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();