01
<?php
02
if (php_sapi_name() != 'cli') {
03
exit("run cli");
04
}
05
06
# php.ini 裡 error_reporting 設置要麼生要麼死
07
# while(true) 太凶猛了,寫日志會占用高的IO
08
//ini_set('error_reporting', E_ERROR);
09
//ini_set('display_errors', 0);
10
set_time_limit(0);
11
12
# 記錄文件
13
$recvfile = './recv.txt';
14
15
# 心跳標記
16
$heartag = "\r\n";
17
18
# 數組長度
19
$datalen = 1024 * 1024;
20
21
$ip = '192.168.125.233';
22
$port = 12345;
23
24
# IPv4, 流, TCP
25
$sockect = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
26
# 綁定服務端必須的
27
if (!socket_bind($sockect, $ip, $port)) {
28
exit("socket bind fail\n");
29
}
30
31
# 監聽
32
socket_listen($sockect);
33
# 不阻塞
34
socket_set_nonblock($sockect);
35
36
$clients = array();
37
38
while (true) {
39
# 接收客戶端連接
40
$client = socket_accept($sockect);
41
if (is_resource($client)) {
42
# 觸發心跳
43
socket_write($client, $heartag, strlen($heartag));
44
$clients[] = $client;
45
printf("client index:%d\n", count($clients));
46
}
47
unset($client);
48
49
if (!empty($clients)) {
50
foreach ($clients AS $idx => &$client) {
51
if (is_resource($client)) {
52
$recvstr = '';
53
# 接收客戶端數據 注意:第四個參數必須為零,這跟手冊上不一樣,還沒搞明白
54
if (socket_recv($client, $recvstr, $datalen, 0) === 0) {
55
socket_close($client);
56
socket_shutdown($client);
57
unset($clients[$idx]);
58
continue;
59
}
60
61
if ($recvstr == $heartag) {
62
# 觸發心跳
63
socket_write($client, $heartag, strlen($heartag));
64
} elseif (trim($recvstr) != "") {
65
# 輸出接收的消息
66
$stdmsg = sprintf("%d:%s\n", $idx, $recvstr);
67
file_put_contents($recvfile, $stdmsg, FILE_APPEND);
68
echo $stdmsg;
69
}
70
}
71
unset($recvstr, $idx);
72
}
73
}
74
# 要睡多久?這是個問題,不睡 CPU 很累, 內存吃的厲害
75
usleep(50000);
76
}
77
78
socket_close($sockect);
79
socket_shutdown($sockect);
80
?>
作者:oodbqpoo