onConnect
Description:
callback Worker::$onConnect
This callback function is triggered when a client establishes a connection with Workerman (after the TCP three-way handshake is completed). The onConnect callback will be triggered only once for each connection.
Note: The onConnect event only indicates that the client has completed the TCP three-way handshake with Workerman. At this point, the client has not sent any data. Therefore, apart from obtaining the other party's IP address through $connection->getRemoteIp(), there is no other data or information available to identify the client. To know who the other party is, the client needs to send authentication data, such as a token or username and password, which can be verified in the onMessage callback.
Since UDP is connectionless, the onConnect callback will not be triggered when using UDP, nor will the onClose callback.
Parameters of the Callback Function
$connection
The connection object, which is the TcpConnection instance, used to operate the client connection, such as sending data, closing the connection, etc.
Example
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('websocket://0.0.0.0:8484');
$worker->onConnect = function(TcpConnection $connection)
{
echo "new connection from ip " . $connection->getRemoteIp() . "\n";
};
// Run the worker
Worker::runAll();
Tip: In addition to using an anonymous function as a callback, you can also refer to here for other callback writing methods.