void Connection::close(mixed $data = '')
Safely closes the connection and triggers the connection's onClose callback.
Although UDP is connectionless, the corresponding AsyncUdpConnection object is kept in memory until the close method is called to release the corresponding UDP connection object; otherwise, this UDP connection object will remain in memory, causing a memory leak.
Parameters
$data
An optional parameter for the data to be sent (if a protocol is specified, the protocol's encode method will be automatically called to package $data), which will close the connection after the data has been sent, subsequently triggering the onClose callback.
The data size must not exceed 65507 bytes; otherwise, the sending will fail.
Example
use Workerman\Worker;
use Workerman\Timer;
use Workerman\Connection\AsyncUdpConnection;
use Workerman\Connection\UdpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('udp://0.0.0.0:1234');
$worker->onWorkerStart = function(){
// 1 second later, start a UDP client, connect to port 1234 and send the string hi
Timer::add(1, function(){
$udp_connection = new AsyncUdpConnection('udp://127.0.0.1:1234');
$udp_connection->onConnect = function(AsyncUdpConnection $udp_connection){
$udp_connection->send('hi');
};
$udp_connection->onMessage = function(AsyncUdpConnection $udp_connection, $data){
// Received data hello from server
echo "recv $data\r\n";
// Close the connection
$udp_connection->close();
};
$udp_connection->connect();
}, null, false);
};
$worker->onMessage = function(UdpConnection $connection, $data)
{
// Received data from AsyncUdpConnection client, return the string hello
$connection->send("hello");
};
Worker::runAll();
After execution, it prints something like:
recv hello