Reputation: 1034
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '127.0.0.1', 100);
socket_listen($socket);
$client = socket_accept($socket);
socket_write($client, 'output');
sleep(10);
socket_close($client);
socket_close($socket);
?>
When I go to the terminal and type nc localhost 100
I get output immediately, as I want.
But when I type "localhost:100
" in the address bar in the browser, the word output is showed up after 10 seconds.
But!
If I change the code to:
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '127.0.0.1', 100);
socket_listen($socket);
$client = socket_accept($socket);
$str = '';
for ($index = 0; $index < 4096; $index++) {
$str .= ' ';
}
socket_write($client, $str);
socket_write($client, 'output');
sleep(10);
socket_close($client);
socket_close($socket);
?>
I get output (and all the spaces before it) on the browser immediately after sending the request.
How can I get the output immediately in the browser without sending a lot of data?
Upvotes: 2
Views: 676
Reputation: 3239
There is the output buffering of PHP, that is possibly enabled. Flush the buffer as described by Samyam A. Or disable it by using: using ob_end_flush();
The browser itself may ignore data, until it's over some limit (~1KB) or the connection was closed. This is due to some optimization. They assumed that the first 1KB of a document doesn't have enough useful information to render a preview of a document. Solution: Send 1KB of dummy data (e.g. whitespaces) at the beginning. Then send data as normal.
There are possibilies that there is a virus scanner or a toolbar that acts as a proxy server which handles HTTP streams in a way that it first fetches a complete block of data (or even the whole document) and when done they process and forward that block. This should not happen, if you work at port 100 (which is a usual trick to prevent such tools from delaying the data stream). More over you work at localhost. If you do have an internet provider between (especially mobile network operators), you'll possibly have your data tunneled through a transparent proxy server, which causes such problems too.
Upvotes: 1
Reputation: 176
You might be seeing this behaviour since in your first case, the data you are sending is too small and thus the output buffer might be keeping it around till enough data is filled or the connection is closed.
try flushing the data using ob_implicit_flush()
or calling ob_flush()
explicitly after each write:
<?php
ob_implicit_flush();
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '127.0.0.1', 100);
socket_listen($socket);
$client = socket_accept($socket);
socket_write($client, 'output');
sleep(10);
socket_close($client);
socket_close($socket);
?>
Upvotes: 2