/* 监听Socket连接 */
if (($ret = socket_listen($sock, 5)) < 0) {
echo "socket_listen() failed: reason: " . socket_strerror($ret) . "\n";
}
/* 永远循环监接受用户连接 */
do {
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
break;
}
/* 发送提示信息给连接上来的用户 */
$msg = "==========================================\r\n" .
" Welcome to the PHP Test Server. \r\n\r\n".
" To quit, type ’quit’. \r\n" .
" To shut down the server type ’shutdown’.\r\n" .
" To get help message type ’help’.\r\n" .
"==========================================\r\n" .
"php> ";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
/* 客户端输入quit命令时候关闭客户端连接 */
if ($buf == ’quit’) {
break;
}
/* 客户端输入shutdown命令时候服务端和客户端都关闭 */
if ($buf == ’shutdown’) {
socket_close($msgsock);
break 2;
}
/* 客户端输入help命令时候输出帮助信息 */
if ($buf == ’help’) {
$msg = " PHP Server Help Message \r\n\r\n".
" To quit, type ’quit’. \r\n" .
" To shut down the server type ’shutdown’.\r\n" .
" To get help message type ’help’.\r\n" .
"php> ";
socket_write($msgsock, $msg, strlen($msg));
continue;
}
/* 客户端输入命令不存在时提示信息 */
$talkback = "PHP: unknow command ’$buf’.\r\nphp> ";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
/* 关闭Socket连接 */
socket_close($sock);
?>
保存以上代码退出。
上面的代码大致就是完成一个类似于Telnet服务器端的功能,就是当服务器端运行该程序的时候,客户端能够连接该服务器的10000端口进行通信。
加上文件的可执行权限:
$ chmod +x /home/heiyeluren/php_daemon2.php
在服务器上执行命令:
$ nohup /home/heiyeluren/php_daemon2.php &
就进入了后台运行,我们通过Windows的客户端telnet上去:
C:\>telnet 192.168.0.1 10000
如果提示:
正在连接到192.168.0.188...不能打开到主机的连接, 在端口 10000: 连接失败
则说明服务器端没有开启,或者上面的程序没有正确执行,请检查php是否 --enable-sockets 功能。如果提示:
==========================================
Welcome to the PHP Test Server.
To quit, type ’quit’.
To shut down the server type ’shutdown’.
To get help message type ’help’.
==========================================
php>
则说明顺利连接上了我们的PHP写的服务器端守护进程,在php>提示符后面能够执行help、quit、shutdown等三个命令,如果命令输入不是这三个,则提示:
php> asdf
PHP: unknow command ’asdf’.
执行help命令可以获取帮助
php> help
PHP Server Help Message
To quit, type ’quit’.
To shut down the server type ’shutdown’.
To get help message type ’help’.
这个服务器端就不介绍了,可以自行扩展。
杀进程跟例子一类似。
[ 总结 ]通过以上学习,我们知道php也可以做守护进程,如果设计的好,功能也会比较强大,不过我们这里只是学习而已,可以自行研究更新。
本文参考了php中文手册,多看手册,对自己非常有好处。
责任编辑:小草