Last active
December 21, 2015 08:19
-
-
Save picasso250/6277302 to your computer and use it in GitHub Desktop.
A small server handel tcp request
一个非常小的服务器,用来监听TCP请求
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
set_time_limit(0); // 无限制的跑下去,跑到天荒地老 | |
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
// 绑定地址和端口 | |
if (!socket_bind($socket, $config['tcp.host'], $config['tcp.port'])) { | |
die('socket bind fail'); | |
} | |
// 开始监听 | |
if (!socket_listen($socket)) { | |
die('socket lisen fail'); | |
} | |
// 这就是我要做一辈子的工作 | |
while (true) { | |
//看看这里有啥要做的么,没有就循环 | |
if (($skt = socket_accept($socket)) === false) { | |
continue; | |
} | |
// fork a child to run service | |
$pid = pcntl_fork(); | |
if ($pid == 0) { | |
// "I am child"; | |
// will do the job | |
socket_close($socket); | |
} else { | |
// "I am father"; | |
// will wait for another request | |
continue; | |
} | |
// ... do something with request | |
socket_close($skt); | |
// 子进程自杀 | |
exit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment