PHP Socket Server_PHP Tutorial

WBOY
Release: 2016-07-13 17:53:13
Original
1352 people have browsed it



01
02
if (php_sapi_name() != 'cli') {
03
exit("run cli");
04
}
05

06
# The error_reporting setting in php.ini is life or death
07
# while(true) is too fierce, writing logs will occupy high IO
08
//ini_set('error_reporting', E_ERROR);
09
//ini_set('display_errors', 0);
10
set_time_limit(0);
11

12
# Record file
13
$recvfile = './recv.txt';
14

15
#Heartbeat mark
16
$heartag = "rn";
17

18
# Array length
19
$datalen = 1024 * 1024;
20

21
$ip = '192.168.125.233';
22
$port = 12345;
23

24
# IPv4, stream, TCP
25
$sockect = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
26
# Required to bind the server
27
if (!socket_bind($sockect, $ip, $port)) {
28
exit("socket bind failn");
29
}
30

31
# Listen
32
socket_listen($sockect);
33
# No blocking
34
socket_set_nonblock($sockect);
35

36
$clients = array();
37

38
while (true) {
39
#Receive client connection
40
$client = socket_accept($sockect);
41
if (is_resource($client)) {
42
# Trigger heartbeat
43
socket_write($client, $heartag, strlen($heartag));
44
$clients[] = $client;
45
printf("client index:%dn", 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
# Receive client data Note: The fourth parameter must be zero, which is different from the manual, I haven’t figured it out yet
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
​​ # Trigger heartbeat
63
socket_write($client, $heartag, strlen($heartag));
64
} elseif (trim($recvstr) != "") {
65
​​ # Output the received message
66
$stdmsg = sprintf("%d:%sn", $idx, $recvstr);
67
File_put_contents($recvfile, $stdmsg, FILE_APPEND);
68
echo $stdmsg;
69
}
70
}
71
unset($recvstr, $idx);
72
}
73
}
74
# How long do you want to sleep? This is a problem. If you don’t sleep, the CPU will be very tired and the memory will be consumed
75
usleep(50000);
76
}
77

78
socket_close($sockect);
79
socket_shutdown($sockect);
80
?>
Author: oodbqpoo

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478071.htmlTechArticle01 ?php 02 if (php_sapi_name() != cli) { 03 exit(run cli); 04 } 05 06 # The error_reporting setting in php.ini is life or death. 07 # while(true) is too fierce. Writing logs will take up a lot of memory...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template