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);
}
?>
\nat the end of some of thefwritecalls. The reason this was causing a problem is becausefgetsis looking for the newline before it returns.feofloop from the server because the client is only sending one line.feofloop in the client to handle the multiple lines sent from the server.if($result =intoif ($result ==because==is a comparison operator (which is what you actually wanted). Inside anifstatement you almost always want to use==instead of=.socket_client.php:
socket_server.php: