Skip to content

Instantly share code, notes, and snippets.

@picasso250
Last active December 21, 2015 08:19
Show Gist options
  • Save picasso250/6277302 to your computer and use it in GitHub Desktop.
Save picasso250/6277302 to your computer and use it in GitHub Desktop.
A small server handel tcp request 一个非常小的服务器,用来监听TCP请求
<?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