所以我有这个服务器代码,它与我的客户端工作。但是它从客户端获取一条消息,并反向发送一条消息。代码如下:SERVER.php
<?php
$host = "127.0.0.1";
$port = 1234;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket'n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket'n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener'n");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection'n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input'n");
// clean up input string
$input = trim($input);
// reverse client input and send back
$output = strrev($input) . "'n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output'n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>
我如何编辑这段代码,使其可以持续运行?当然,客户端不必熬夜,它只需要打开一个新的套接字,发送消息,从服务器获取消息并关闭套接字。下次我想发送消息时,我将再执行上一步。
现在,如果我发送消息并从服务器获得响应,它们都关闭套接字。请帮我修改一下服务器端,让它不会关闭套接字,等待新的连接。
我试图添加一个while循环,但一旦客户端关闭,服务器再次关闭,说它无法再从客户端读取。
谢谢
我明白了。你们大多数人都能像我一样通过while()循环来解决这个问题。但是,您不能仅仅将代码放入while语句中,就期望它能正常工作。正确的做法如下:
<?php
$host = "127.0.0.1";
$port = 1234;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket'n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket'n");
while(true) {
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener'n");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection'n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input'n");
// clean up input string
$input = trim($input);
// reverse client input and send back
$output = strrev($input) . "'n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output'n");
}
// close sockets
socket_close($spawn);
socket_close($socket);
?>
如果你试图把while放在任何其他地方,它将引入一个错误。D
接受后需要进行fork -参见这里http://php.net/manual/en/function.pcntl-fork.php
accept需要在循环中。在accept之后,fork一个进程来处理这个客户端。
。
while (TRUE)
{
$spawn = socket_accept($socket) or die("Could not accept incoming connection'n");
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
socket_close($spawn);
} else {
// we are the child
// Use $spawn for communication as you see fit
// exit();
}
}
你需要使用信号处理程序来清理僵尸进程。
"蛮力"方式是将代码插入到无限循环中。
While(1){
.
.
}
另一种方式,在收到你的消息后,你可以递归地调用你的脚本
while( TRUE ) {
// your code
}