UdpServer.php
1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?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();