保存以上代码退出。#! /usr/local/php/bin/php
/* 设置不显示任何错误 */
error_reporting(0);
/* 脚本超时为无限 */
set_time_limit(0);
/* 开始固定清除 */
ob_implicit_flush();
/* 本机的IP和需要开放的端口 */
$address = ‘192.168.0.1′;
$port = 10000;
/* 产生一个Socket */
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) /* 把IP地址端口进行绑定 */
if (($ret = socket_bind($sock, $address, $port)) /* 监听Socket连接 */
if (($ret = socket_listen($sock, 5)) /* 永远循环监接受用户连接 */
do {
if (($msgsock = socket_accept($sock)) /* 发送提示信息给连接上来的用户 */
$msg = “==========================================rn” .
” Welcome to the PHP Test Server. rnrn”.
” To quit, type ‘quit’. rn” .
” To shut down the server type ’shutdown’.rn” .
” To get help message type ‘help’.rn” .
”==========================================rn” .
”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 rnrn”.
” To quit, type ‘quit’. rn” .
” To shut down the server type ’shutdown’.rn” .
” To get help message type ‘help’.rn” .
”php> “;
socket_write($msgsock, $msg, strlen($msg));
continue;
}
/* 客户端输入命令不存在时提示信息 */
$talkback = “PHP: unknow command ‘$buf’.rnphp> “;
socket_write($msgsock, $talkback, strlen($talkback));
echo “$bufn”;
} 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’.
这个服务器端就不介绍了,可以自行扩展。
