gpt4 book ai didi

php - 为什么需要MINUTE才能从服务器获得响应?

转载 作者:行者123 更新时间:2023-12-03 11:54:21 24 4
gpt4 key购买 nike

我是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_*函数。阅读 this以获取更多信息。

关于php - 为什么需要MINUTE才能从服务器获得响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com