Nathan Yonkee / Mbed OS mbed-os-tcp-server-example
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>\r\n"
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 DigitalIn swtch(PD_14);
00028 
00029 int main() {
00030     printf("Basic HTTP server example\n");
00031 
00032     EthernetInterface eth;
00033     /* eth.set_network("192.168.1.101", "255.255.255.0","192.168.1.1"); */
00034     eth.connect();
00035 
00036     printf("The target IP address is '%s'\n", eth.get_ip_address());
00037     printf("The target netmask is '%s'\n", eth.get_netmask());
00038     printf("The target gateway is '%s'\n", eth.get_gateway());
00039 
00040     TCPServer srv;
00041     TCPSocket clt_sock;
00042     SocketAddress clt_addr;
00043 
00044     /* Open the server on ethernet stack */
00045     srv.open(&eth);
00046 
00047     /* Bind the HTTP port (TCP 80) to the server */
00048     srv.bind(eth.get_ip_address(), 80);
00049 
00050     /* Can handle 5 simultaneous connections */
00051     srv.listen(5);
00052     while (true) {
00053     srv.accept(&clt_sock, &clt_addr);
00054         printf("accept %s:%d\n", clt_addr.get_ip_address(), clt_addr.get_port());
00055         clt_sock.send(HTTP_RESPONSE, strlen(HTTP_RESPONSE));
00056         /* clt_sock.send("hi\r\n", strlen("hi\r\n")); */
00057     }
00058 }