Closing Unauthenticated Connections
Problem:
How to close client connections that have not sent any data within a specified time frame, such as automatically closing the connection if no data is received for 30 seconds? The purpose is to require unauthenticated connections to authenticate within the specified time.
Answer:
use Workerman\Worker;
use Workerman\Timer;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('xxx://x.x.x.x:x');
$worker->onConnect = function(TcpConnection $connection)
{
// Temporarily add an auth_timer_id property to the $connection object to store the timer id
// Set a timer for 30 seconds to close the connection, requiring the client to send authentication within 30 seconds to clear the timer
$connection->auth_timer_id = Timer::add(30, function()use($connection){
$connection->close();
}, null, false);
};
$worker->onMessage = function(TcpConnection $connection, $msg)
{
$msg = json_decode($msg, true);
switch($msg['type'])
{
case 'login':
...略
// Authentication successful, delete the timer to prevent the connection from being closed
Timer::del($connection->auth_timer_id);
break;
... 略
}
... 略
}