UdpServer.php 1.21 KB
<?php

require_once __DIR__.'/Sender.php';

$serv = new swoole_server("0.0.0.0", Config::udp_port, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); 
$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('Packet', function (swoole_server $serv, $data, $addr)
{
    $ip = $addr['address'];
    
    $ouput = "UDP Request--\n";
    $ouput .= sprintf("Receive request ip: %s, server_socket: %s\n", $ip, $addr['server_socket']);
    $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'=>$ip,
        'hostname'=>!empty($data['hostname']) ? $data['hostname'] : gethostbyaddr($ip),
    );
    $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();