test

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #if !FEATURE_LWIP
00002     #error [NOT_SUPPORTED] LWIP not supported for this target
00003 #endif
00004 
00005 #include "mbed.h"
00006 #include "EthernetInterface.h"
00007 #include "TCPServer.h"
00008 #include "TCPSocket.h"
00009 
00010 #define HTTP_STATUS_LINE "HTTP/1.0 200 OK"
00011 #define HTTP_HEADER_FIELDS "Content-Type: text/html; charset=utf-8"
00012 #define HTTP_MESSAGE_BODY ""                                     \
00013 "<html>" "\r\n"                                                  \
00014 "  <body style=\"display:flex;text-align:center\">" "\r\n"       \
00015 "    <div style=\"margin:auto\">" "\r\n"                         \
00016 "      <h1>Hello World</h1>" "\r\n"                              \
00017 "      <p>It works !</p>" "\r\n"                                 \
00018 "    </div>" "\r\n"                                              \
00019 "  </body>" "\r\n"                                               \
00020 "</html>"
00021 
00022 #define HTTP_RESPONSE HTTP_STATUS_LINE "\r\n"   \
00023                       HTTP_HEADER_FIELDS "\r\n" \
00024                       "\r\n"                    \
00025                       HTTP_MESSAGE_BODY "\r\n"
00026 
00027 int main()
00028 {
00029     printf("Basic HTTP server example\n");
00030     
00031     EthernetInterface eth;
00032     eth.connect();
00033     
00034     printf("The target IP address is '%s'\n", eth.get_ip_address());
00035     
00036     TCPServer srv;
00037     TCPSocket clt_sock;
00038     SocketAddress clt_addr;
00039     
00040     /* Open the server on ethernet stack */
00041     srv.open(&eth);
00042     
00043     /* Bind the HTTP port (TCP 80) to the server */
00044     srv.bind(eth.get_ip_address(), 80);
00045     
00046     /* Can handle 5 simultaneous connections */
00047     srv.listen(5);
00048     
00049     while (true) {
00050         srv.accept(&clt_sock, &clt_addr);
00051         printf("accept %s:%d\n", clt_addr.get_ip_address(), clt_addr.get_port());
00052         clt_sock.send(HTTP_RESPONSE, strlen(HTTP_RESPONSE));
00053     }
00054 }