From @fpoto on December 2, 2013 16:18
I am trying to set up a WiFi web server following one of many tutorials around there. I get terrible performance with this code:
# include <Streaming.h>
...
client << F("HTTP/1.1 200 OK") << endl
<< F("Content-Type: text/html") << endl
<< F("Connection: keep-alive") << endl << endl;
// send web page
webFile = SD.open("index.htm"); // open web page file
if (webFile)
while(webFile.available())
client.write(webFile.read()); // send web page to client
webFile.close();
...
As you see, one byte at a time is read from a file on SD card and is immediately written to the TCP stream. What happens is strange. This is an excerpt of a tcpdump where the timing of each packet is relative to the previous packet:
00:00:02.030797 IP arduino.www > casapot.38839: Flags [P.], seq 199:231, ack 8, win 2041, length 32
00:00:00.000043 IP casapot.38839 > arduino.www: Flags [.], ack 231, win 5840, length 0
00:00:00.001829 IP arduino.www > casapot.38839: Flags [P.], seq 231:232, ack 8, win 2041, length 1
00:00:00.000047 IP casapot.38839 > arduino.www: Flags [.], ack 232, win 5840, length 0
00:00:02.030607 IP arduino.www > casapot.38839: Flags [P.], seq 232:264, ack 8, win 2041, length 32
00:00:00.000049 IP casapot.38839 > arduino.www: Flags [.], ack 264, win 5840, length 0
00:00:00.001546 IP arduino.www > casapot.38839: Flags [P.], seq 264:265, ack 8, win 2041, length 1
00:00:00.000033 IP casapot.38839 > arduino.www: Flags [.], ack 265, win 5840, length 0
00:00:02.030799 IP arduino.www > casapot.38839: Flags [P.], seq 265:297, ack 8, win 2041, length 32
00:00:00.000094 IP casapot.38839 > arduino.www: Flags [.], ack 297, win 5840, length 0
00:00:00.002027 IP arduino.www > casapot.38839: Flags [P.], seq 297:298, ack 8, win 2041, length 1
00:00:00.000092 IP casapot.38839 > arduino.www: Flags [.], ack 298, win 5840, length 0
This means that Arduino sends a 32-byte long packet immediately followed by a 1-byte long packet, then waits 2 seconds before repeating again!!
If I replace this:
while(webFile.available())
client.write(webFile.read()); // send web page to client
with this:
while(webFile.available()) {
const byte maxn = 32;
byte buf[maxn];
client.write(buf, webFile.read(buf, maxn)); // send web page to client
}
the WiFI shield sends 512-byte long packets, all in a matter of milliseconds.
Copied from original issue: arduino/Arduino#1712