Alternative TCPSocket example using an HTTP GET to read a short "helloworld" text web page using a different server

Fork of ARMs demo HTTP socket demo. ARM's server was redirected and the demo was no longer working. An alternative server was setup and the code was modified to display the web page text in addition to just "200 OK". Only works for a very short web page - buffer only 400 characters but RAM is running out on the LPC1768 in the demo! Data read from the web page is read and parsed to control the mbed's 4 LEDs for a basic IoT demo.

Committer:
mab5449
Date:
Thu Jan 19 11:46:10 2017 -0600
Revision:
0:6b383744246e
Child:
1:965d7fb768b6
Ported mbed OS 2 to mbed OS 5

Who changed what in which revision?

UserRevisionLine numberNew contents of line
mab5449 0:6b383744246e 1 #include "mbed.h"
mab5449 0:6b383744246e 2 #include "EthernetInterface.h"
mab5449 0:6b383744246e 3
mab5449 0:6b383744246e 4 // Network interface
mab5449 0:6b383744246e 5 EthernetInterface net;
mab5449 0:6b383744246e 6
mab5449 0:6b383744246e 7 // Socket demo
mab5449 0:6b383744246e 8 int main() {
mab5449 0:6b383744246e 9 // Bring up the ethernet interface
mab5449 0:6b383744246e 10 printf("Ethernet socket example\n");
mab5449 0:6b383744246e 11 net.connect();
mab5449 0:6b383744246e 12
mab5449 0:6b383744246e 13 // Show the network address
mab5449 0:6b383744246e 14 const char *ip = net.get_ip_address();
mab5449 0:6b383744246e 15 printf("IP address is: %s\n", ip ? ip : "No IP");
mab5449 0:6b383744246e 16
mab5449 0:6b383744246e 17 // Open a socket on the network interface, and create a TCP connection to mbed.org
mab5449 0:6b383744246e 18 TCPSocket socket;
mab5449 0:6b383744246e 19 socket.open(&net);
mab5449 0:6b383744246e 20 socket.connect("developer.mbed.org", 80);
mab5449 0:6b383744246e 21
mab5449 0:6b383744246e 22 // Send a simple http request
mab5449 0:6b383744246e 23 char sbuffer[] = "GET / HTTP/1.1\r\nHost: developer.mbed.org\r\n\r\n";
mab5449 0:6b383744246e 24 int scount = socket.send(sbuffer, sizeof sbuffer);
mab5449 0:6b383744246e 25 printf("sent %d [%.*s]\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
mab5449 0:6b383744246e 26
mab5449 0:6b383744246e 27 // Recieve a simple http response and print out the response line
mab5449 0:6b383744246e 28 char rbuffer[64];
mab5449 0:6b383744246e 29 int rcount = socket.recv(rbuffer, sizeof rbuffer);
mab5449 0:6b383744246e 30 printf("recv %d [%.*s]\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
mab5449 0:6b383744246e 31
mab5449 0:6b383744246e 32 // Close the socket to return its memory and bring down the network interface
mab5449 0:6b383744246e 33 socket.close();
mab5449 0:6b383744246e 34
mab5449 0:6b383744246e 35 // Bring down the ethernet interface
mab5449 0:6b383744246e 36 net.disconnect();
mab5449 0:6b383744246e 37 printf("Done\n");
mab5449 0:6b383744246e 38 }