![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
A small example of TCP server over ethernet for mbed-os.
Revision 3:48f60b2918aa, committed 2018-05-11
- Comitter:
- nenad
- Date:
- Fri May 11 15:40:50 2018 +0000
- Parent:
- 2:e72bc303ea90
- Commit message:
- PMK2018;
Changed in this revision
main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/main.cpp Mon Jun 26 09:28:54 2017 +0000 +++ b/main.cpp Fri May 11 15:40:50 2018 +0000 @@ -1,54 +1,38 @@ -#if !FEATURE_LWIP - #error [NOT_SUPPORTED] LWIP not supported for this target -#endif - #include "mbed.h" +#include "TCPSocket.h" #include "EthernetInterface.h" -#include "TCPServer.h" -#include "TCPSocket.h" -#define HTTP_STATUS_LINE "HTTP/1.0 200 OK" -#define HTTP_HEADER_FIELDS "Content-Type: text/html; charset=utf-8" -#define HTTP_MESSAGE_BODY "" \ -"<html>" "\r\n" \ -" <body style=\"display:flex;text-align:center\">" "\r\n" \ -" <div style=\"margin:auto\">" "\r\n" \ -" <h1>Hello World</h1>" "\r\n" \ -" <p>It works !</p>" "\r\n" \ -" </div>" "\r\n" \ -" </body>" "\r\n" \ -"</html>" - -#define HTTP_RESPONSE HTTP_STATUS_LINE "\r\n" \ - HTTP_HEADER_FIELDS "\r\n" \ - "\r\n" \ - HTTP_MESSAGE_BODY "\r\n" +EthernetInterface eth; +TCPSocket socket; int main() { - printf("Basic HTTP server example\n"); - - EthernetInterface eth; + printf("Basic TCP client example\n"); + + // Brings up the network interface eth.connect(); - - printf("The target IP address is '%s'\n", eth.get_ip_address()); - - TCPServer srv; - TCPSocket clt_sock; - SocketAddress clt_addr; - - /* Open the server on ethernet stack */ - srv.open(ð); - - /* Bind the HTTP port (TCP 80) to the server */ - srv.bind(eth.get_ip_address(), 80); - - /* Can handle 5 simultaneous connections */ - srv.listen(5); - - while (true) { - srv.accept(&clt_sock, &clt_addr); - printf("accept %s:%d\n", clt_addr.get_ip_address(), clt_addr.get_port()); - clt_sock.send(HTTP_RESPONSE, strlen(HTTP_RESPONSE)); - } -} + const char *ip = eth.get_ip_address(); + const char *mac = eth.get_mac_address(); + printf("IP address is: %s\n", ip ? ip : "No IP"); + printf("MAC address is: %s\n", mac ? mac : "No MAC"); + + // Open a socket on the network interface, and create a TCP connection to mbed.org + socket.open(ð); + socket.connect("192.168.0.108", 80); + + // Send data + char sbuffer[] = "12345"; + int scount = socket.send(sbuffer, sizeof sbuffer); + printf("sent %d [%.*s]\r\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer); + + // Recieve a simple http response and print out the response line + char rbuffer[64]; + int rcount = socket.recv(rbuffer, sizeof rbuffer); + printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer); + + // Close the socket to return its memory and bring down the network interface + socket.close(); + eth.disconnect(); + + printf("Done\n"); +} \ No newline at end of file