当我通过命令行运行下面的两个文件时(首先启动socket_server,然后是socket_client),在服务器向socket_client发送任何输出之前有一个很长的延迟(~60s)。有没有办法减少这个差距,或任何暗示导致问题的提示?以下是我的两个代码段:
<?php
$fp = stream_socket_client("tcp://127.0.0.1:8000", $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
}
else {
fwrite($fp, "2");
echo fgets($fp, 1024);
}
fclose($fp);
?>
<?php
$socket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
while (!feof($conn)) {
$result = fgets($conn, 1024);
if($result = "2"){
fwrite($conn, "Hullo there");
}
else{
fwrite($conn, "Hullo here\n");
}
}
fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
fclose($conn);
}
fclose($socket);
}
?>
答案 0 :(得分:3)
\n
来电时发送fwrite
。导致问题的原因是因为fgets
在返回之前正在寻找换行符。feof
循环,因为客户端只发送一行。feof
循环来处理从服务器发送的多行。if($result =
更改为if ($result ==
,因为==
是一个比较运算符(这是您真正想要的)。在if
声明中,您几乎总是希望使用==
代替=
。<强> socket_client.php:强>
<?php
$fp = stream_socket_client("tcp://127.0.0.1:8000", $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "2\n");
while (!feof($fp)) {
echo fgets($fp, 1024);
}
}
fclose($fp);
?>
<强> socket_server.php:强>
<?php
$socket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
$result = fgets($conn, 1024);
if ($result == "2\n") {
fwrite($conn, "Hullo there\n");
} else {
fwrite($conn, "Hullo here\n");
}
fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
fclose($conn);
}
fclose($socket);
}
?>