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

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "EthernetInterface.h"
00003 BusOut leds(LED1,LED2,LED3,LED4); //LEDs are controlled by web page text data
00004 // Network interface
00005 EthernetInterface net;
00006 
00007 // Socket demo
00008 int main()
00009 {
00010     // Show MAC in case it is needed to enable DHCP on a secure network
00011     char mac[6];
00012     mbed_mac_address(mac);
00013     printf("\r\rmbed's MAC address is %02x:%02x:%02x:%02x:%02x:%02x\n\r", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
00014     // Bring up the ethernet interface
00015     printf("Waiting for IP address from DHCP Server\n\r");
00016     wait(1.0);
00017     net.connect();
00018     printf("\n\rEthernet socket example\n\r");
00019 
00020     // Show the network address
00021     const char *ip = net.get_ip_address();
00022     printf("IP address is: %s\n\r", ip ? ip : "Timeout - No IP obtained");
00023 
00024     // Open a socket on the network interface, and create a TCP connection to mbed.org
00025     TCPSocket socket;
00026     socket.open(&net);
00027     socket.connect("hamblen.ece.gatech.edu", 80);
00028 
00029     // Send a simple http request
00030     char sbuffer[] = "GET /hello.txt HTTP/1.1\r\nHost: hamblen.ece.gatech.edu\r\n\r\n";
00031     int scount = socket.send(sbuffer, sizeof sbuffer);
00032     //print out packet
00033     printf("sent %d [%.*s]\n\r", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
00034 
00035     // Recieve a simple http response and print out the response line and text
00036     char rbuffer[400]; //enough for a very short text page - almost out of RAM!
00037     int rcount = socket.recv(rbuffer, sizeof rbuffer);
00038     rbuffer[rcount] = 0; //terminate to print as a C string;
00039     //Print packet read from HTTP web page server
00040     printf("recv %d [%.*s]\n\r", rcount, strstr(rbuffer, "\r\n"), rbuffer);
00041 
00042     // Close the socket to return its memory and bring down the network interface
00043     socket.close();
00044 
00045     // Basic IoT demo controlling mbeds 4 LEDs from Internet web page's ASCII text data
00046     // Web page demo contains a line "Data:0101"
00047     char *data;
00048     data = strstr(rbuffer,"Data:"); //Find Data: line on web page with '0's or '1's
00049     data = data + 5; //Skip to data
00050     for (int i=0; i<=3; i++) //Parse 4 web page characters to control LEDs
00051         leds[i] = data[i] - '0'; //convert ASCII '0' or '1's to binary to control 4 leds
00052     //Another device could change the web page contents to control LEDs from anywhere
00053 
00054     // Bring down the ethernet interface
00055     net.disconnect();
00056     printf("Done\n\r");
00057 }