2013-03-06 48 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

相關問題