Hardware Reference
In-Depth Information
In the main loop, you'll spend all
your time listening for a connec-
tion from a remote client. When you get
a connection, you'll wait for the client
to make an HTTP request, like you saw
in Chapter 3. This loop won't reply to
the client, but it will show you what the
client requests.
8
void loop()
{
// listen for incoming clients
Client client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char thisChar = client.read();
Serial.write(thisChar);
}
}
// close the connection:
client.stop();
}
}
Run this sketch with the Ethernet module
attached to your router and the Serial Monitor
open. Then open a browser window and go to
the Arduino's address. Using the example as shown, you'd
go to http://192.168.1.20. You won't see anything in the
browser, but you will see the HTTP request come through
in the Serial Monitor. Now you're seeing what the server
saw when you made HTTP requests in Chapter 3. A typical
request will look like this:
For now, you can keep it simple and just look for the end
of the request, which will be a linefeed ( \n or ASCII 10),
followed by a carriage return ( \r or ASCII 13), followed by
another linefeed. Figure 4-5 shows what happens in the
code that follows.
X
Client
connects
GET / HTTP/1.1
Host: 192.168.1.1
Connection: keep-alive
Accept: application/xml,application/xhtml+xml,text/
html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X
10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
Chrome/8.0.552.215 Safari/534.10
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Check for
incoming
bytes
increment
line length
carriage
return
any other value
Read & print
received byte
disconnect
linefeed
You can ignore most of the HTTP parameters, but two
pieces are useful: the first line, where you see what the
client is requesting; and the end, where it sends a blank
line to finish the request. In this case, the first line shows
that the client is asking for the main index page at the
root of the server, signified by the / in GET / . You're only
going to have one result to return, but in the future, you will
write a more complex server that looks at this part of the
request and responds with different results depending on
what's requested.
send
response
set line
length to 0
line length > 0?
no
yes
Figure 4-5
Logic flow for a simple server.
 
Search WWH ::




Custom Search