PHP Socket Server_PHP教程

來源:互聯網
上載者:User
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

http://www.bkjia.com/PHPjc/478071.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/478071.htmlTechArticle01 ?php 02 if (php_sapi_name() != cli) { 03 exit(run cli); 04 } 05 06 # php.ini 裡 error_reporting 設定要麼生要麼死 07 # while(true) 太兇猛了,寫日誌會佔用高的...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.