TcpServer.php 1.17 KB
<?php

require_once __DIR__.'/Sender.php';

$serv = new swoole_server("0.0.0.0", Config::tcp_port);
$serv->set(array(
    'worker_num' => Config::worker_num,
    'daemonize' => Config::daemonize, //是否作为守护进程
    'log_file' => Config::log_file,
));

$serv->on('start', function (swoole_server $serv){
    echo "Client:Start.\n";
});

$serv->on('connect', function (swoole_server $serv, $fd){
    //echo "Client:Connect.\n";
});

$serv->on('receive', function (swoole_server $serv, $fd, $from_id, $data) 
{
    $serv->close($fd);
    
    $ouput = "TCP Request--\n";
    $ouput .= sprintf("Receive request fd: %d\n", $fd);
    $ouput .= date('Y-m-d H:i:s')."\n";
    $ouput .= "Request data: \n";
    $ouput .= $data;
    $ouput .= "\r\n\r\n";
    Sender::log($ouput);
    
    $data = unserialize(trim($data));
    if (!is_array($data)){
        return;
    }
    
    $tags = array(
        'ip'=>'',
        'hostname'=>!empty($data['hostname']) ? $data['hostname'] : '',
    );
    $type = !empty($data['type']) ? $data['type'] : '';
    Sender::add($type,$data,$tags);
});

$serv->on('close', function (swoole_server $serv, $fd) {
    echo "Client: Close.\n";
});

$serv->start();