开发者

Long delay between stream_socket_server and stream_socket_client on the same PC

When I run the two files below through the command line, (first start socket_server, then socket_client) there is a long delay (~60s) before any output is sent to socket_client by the server. Is there a way to reduce this gap, or any hints as to what is causing the problem? Here are my two code snippets:

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


  • You were forgetting to send \n at the end of some of the fwrite calls. The reason this was causing a problem is because fgets is looking for the newline before it returns.
  • I removed the feof loop from the server because the client is only sending one line.
  • I added the feof loop in the client to handle the multiple lines sent from the server.
  • I changed if($result = into if ($result == because == is a comparison operator (which is what you actually wanted). Inside an if statement you almost always want to use == instead of =.

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

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜