Roy van Dam / Mbed 2 deprecated TCP_Client_Example

Dependencies:   mbed mbed-rtos EthernetInterface NetworkAPI

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 
00004 #include "NetworkAPI/buffer.hpp"
00005 #include "NetworkAPI/ip/address.hpp"
00006 #include "NetworkAPI/tcp/socket.hpp"
00007 
00008 int
00009 main()
00010 {
00011     EthernetInterface interface;
00012     interface.init();
00013     interface.connect();
00014     printf("IP Address is %s\n\r", interface.getIPAddress());
00015   
00016     int result;
00017   
00018     network::tcp::Socket socket;
00019     network::Buffer buffer(256);
00020     std::string request("GET /media/uploads/donatien/hello.txt HTTP/1.1\r\nHost: %s\r\n\r\n");
00021     
00022     if (socket.open() < 0) {
00023         printf("Failed to open TCP Socket\n\r");
00024         return -1;
00025     }
00026     
00027     if (socket.connect("mbed.org", 80) < 0) {
00028         printf("Failed to connect with mbed.org\n\r");
00029         return -1;
00030     }
00031     
00032     if (socket.write((void *)request.data(), request.size()) < 0) {
00033         printf("Failed to write HTTP request\n\r");
00034         return -1;
00035     }
00036     
00037     do
00038     {
00039         result = socket.read(buffer);   
00040         printf("Received %d bytes:\n\r%s\n\r", result, (char *)buffer.data());
00041     } while(result > 0);
00042     
00043     socket.close();
00044     return 0;
00045 }