stream_socket_server和stream_socket_client在同一台PC上的长时间延迟

时间:2010-12-24 18:14:33

标签: php sockets stream-socket-client

当我通过命令行运行下面的两个文件时(首先启动socket_server,然后是socket_client),在服务器向socket_client发送任何输出之前有一个很长的延迟(~60s)。有没有办法减少这个差距,或任何暗示导致问题的提示?以下是我的两个代码段:

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");
       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)) {
    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);
}
?>

1 个答案:

答案 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);
}

?>