2013-03-06 62 views
2

我是新来的PHP套接字编程,我发现了一个实验的例子,但是当我与我的服务器通话时,在服务器套接字关闭之前需要一分钟才能获得响应。为什么需要MINUTE从服务器获得响应?

我有以下代码: 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> 
+0

你得到一个错误? – 2013-03-06 06:17:46

+1

仔细阅读问题。 OP在问为什么响应需要1分钟。 – 2013-03-06 06:19:11

+0

为什么我花了一分钟才明白你? – 2013-03-06 06:35:56

回答

1

如果我没有记错的话,你的服务器首先读取第一和然后写回的响应。尽管您的客户端会执行相同的操作,但希望看到您的服务器无法发送的“欢迎消息”。所以他们都坐在那里等待彼此的数据。也许评论一下你得到(看似不存在)的欢迎信息应该能够缓解这种僵局。

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

那么,或者确保在客户端连接后立即从服务器实际发送欢迎消息。

你说,它工作在终端的时候了。我只能猜测某个换行符(作为ENTER键的结果)正在发送,它在客户端实现了fgets呼叫。

而且好像你应该能够使用您的服务器所使用的客户端以及在socket_*功能。阅读this获取更多信息。

+0

感谢它的工作,甚至没有注意到这一行..LOL – Brian 2013-03-06 07:14:50

+0

@ A.S.Roma当然,很高兴我可以帮助。 – 2013-03-06 07:15:55

相关问题