미인증 연결 종료
문제:
정해진 시간 내에 데이터를 전송하지 않은 클라이언트를 어떻게 종료할 수 있을까요?
예를 들어 30초 내에 메시지를 받지 못하면 자동으로 클라이언트 연결을 종료합니다.
목적은 미인증 연결이 정해진 시간 내에 인증해야만 한다는 것입니다.
답변:
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)
{
// 임시로 $connection 객체에 auth_timer_id 속성을 추가하여 타이머 id를 저장합니다.
// 30초 후에 연결 종료, 클라이언트가 30초 내에 인증을 보낼 경우 타이머를 삭제합니다.
$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':
...생략
// 인증 성공, 타이머 삭제, 연결이 종료되는 것을 방지합니다.
Timer::del($connection->auth_timer_id);
break;
... 생략
}
... 생략
}