Home > php教程 > php手册 > PHP Socket Server

PHP Socket Server

WBOY
Release: 2016-06-13 10:51:14
Original
1377 people have browsed it


 
01
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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template