为什么需要一分钟才能从服务器获得响应


Why it takes a MINUTE to get a respond from server?

我是PHP套接字编程的新手,我找到了一个例子来实验,但是当我与服务器交谈时,在服务器套接字关闭之前需要一分钟才能得到响应。

我有以下代码: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);
?>

如何让它立即响应?由于

当我在终端中运行客户端代码时,我立即得到响应。但是,当我添加一个文本框从浏览器中运行它时,它需要1分钟才能获得显示在浏览器上的响应。

如果您需要查看我的CLIENT.php

<html>
<head>
</head>
<body>
<form action="<? echo $PHP_SELF; ?>" method="post">
Enter some text:<br>
<input type="Text" name="message" size="15"><input type="submit" name="submit" value="Send">
</form>
<?php
if (isset($_POST['submit']))
{
// form submitted
// where is the socket server?
$host="127.0.0.1";
$port = 1234;
// open a client connection
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp)
{
$result = "Error: could not open socket connection";
}
else
{
// get the welcome message
fgets ($fp, 1024);
// write the user string to the socket
fputs ($fp, $_POST['message']);
// get the result
$result .= fgets ($fp, 1024);
// close the connection
fputs ($fp, "exit");
fclose ($fp);
// trim the result and remove the starting ?
$result = trim($result);
// now print it to the browser
}
?>
Server said: <b><? echo $result; ?></b>
<?
}
?>
</body>
</html>

如果我没有弄错的话,您的服务器首先读取,然后,然后写回响应。你的客户端做同样的事情,期待一个"欢迎消息",我看不到你的服务器曾经发送。所以它们都坐在那里等待对方的数据。也许注释掉获得(看似不存在的)欢迎消息的行应该可以缓解这种僵局。

// get the welcome message
// fgets ($fp, 1024);

那,或者一定要在客户端连接时从服务器发送一个欢迎消息。

你说它在终端机里马上就能工作。我只能猜测,以某种方式正在发送一个换行符(作为ENTER键的结果),它在客户端完成了fgets调用。

似乎你也应该能够在客户端中使用服务器中使用的socket_*函数。