Simple TCP Echo Server

Dependencies:   EthernetInterface mbed-rtos mbed

Dependents:   HTTPDcgi

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 #define ECHO_SERVER_PORT   7
00005  
00006 int main (void) {
00007     EthernetInterface eth;
00008     eth.init(); //Use DHCP
00009     eth.connect();
00010     printf("\nServer IP Address is %s\n", eth.getIPAddress());
00011     
00012     TCPSocketServer server;
00013     server.bind(ECHO_SERVER_PORT);
00014     server.listen();
00015     
00016     while (true) {
00017         printf("\nWait for new connection...\n");
00018         TCPSocketConnection client;
00019         server.accept(client);
00020         client.set_blocking(false, 1500); // Timeout after (1.5)s
00021         
00022         printf("Connection from: %s\n", client.get_address());
00023         char buffer[256];
00024         while (true) {
00025             int n = client.receive(buffer, sizeof(buffer));
00026             if (n <= 0) break;
00027             
00028             // print received message to terminal
00029             buffer[n] = '\0';
00030             printf("Received message from Client :'%s'\n",buffer);
00031             
00032             // reverse the message
00033             char temp;
00034             for(int f = 0, l = n-1; f<l; f++,l--){
00035                 temp = buffer[f];
00036                 buffer[f] = buffer[l];
00037                 buffer[l] = temp;
00038                 }
00039             
00040             // print reversed message to terminal
00041             printf("Sending message to Client: '%s'\n",buffer);
00042             
00043             // Echo received message back to client
00044             client.send_all(buffer, n);
00045             if (n <= 0) break;
00046         }
00047         
00048         client.close();
00049     }
00050 }
00051