reConnect Method
void AsyncTcpConnection::reConnect(float $delay = 0)
(Requires Workerman version >= 3.3.5)
Reconnect. This is generally called in the onClose callback to implement reconnection after a disconnection.
If the connection is dropped due to network issues or the other party's service restart, this method can be called to achieve reconnection.
Parameters
$delay
The delay before executing the reconnection. The unit is seconds and supports decimals, allowing precision up to milliseconds.
If not provided or if the value is 0, it means to reconnect immediately.
It is best to pass a parameter to delay the reconnection to avoid excessive CPU usage on the local machine due to continuous failures in connecting to the other party's service.
Return Value
No return value
Example
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker();
$worker->onWorkerStart = function($worker)
{
$con = new AsyncTcpConnection('ws://echo.websocket.org:80');
$con->onConnect = function(AsyncTcpConnection $con) {
$con->send('hello');
};
$con->onMessage = function(AsyncTcpConnection $con, $msg) {
echo "recv $msg\n";
};
$con->onClose = function(AsyncTcpConnection $con) {
// If the connection is dropped, reconnect after 1 second
$con->reConnect(1);
};
$con->connect();
};
Worker::runAll();
Note
After a successful reconnection by calling reconnect, the $con's onConnect method will be called again (if it is set). Sometimes we want the onConnect method to execute only once and not trigger again during reconnections. See the example below:
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker();
$worker->onWorkerStart = function($worker)
{
$con = new AsyncTcpConnection('ws://echo.websocket.org:80');
$con->onConnect = function(AsyncTcpConnection $con) {
static $is_first_connect = true;
if (!$is_first_connect) return;
$is_first_connect = false;
$con->send('hello');
};
$con->onMessage = function(AsyncTcpConnection $con, $msg) {
echo "recv $msg\n";
};
$con->onClose = function(AsyncTcpConnection $con) {
// If the connection is dropped, reconnect after 1 second
$con->reConnect(1);
};
$con->connect();
};
Worker::runAll();