Test to demonstrate that TCP sockets lock up

Dependencies:   EthernetInterface mbed-rtos mbed

Fork of TCPSocket_HelloWorld by mbed official

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 RETRIES_ALLOWED 5
00005 
00006 Serial pc2(USBTX, USBRX);
00007 EthernetInterface eth;
00008 DigitalOut led1(LED1);
00009 
00010 int main()
00011 {
00012 
00013     pc2.baud(115200);
00014     printf("Initialising...\n");
00015     set_time(0);
00016 
00017     // use DHCP
00018     eth.init();
00019 
00020     // attempt DHCP and if timing out then try again
00021     while (eth.connect()) {
00022         printf("DHCP timeout\n");
00023     };
00024 
00025     // successful DHCP
00026     printf("IP Address is %s\n", eth.getIPAddress());
00027 
00028     // loop forever
00029     while (true) {
00030 
00031         // new non blocking socket
00032         TCPSocketConnection sock;
00033         sock.set_blocking(false);
00034 
00035         // toggle led to indicate activity
00036         led1 = !led1;
00037 
00038         // attempt socket connection and if failure then loop again
00039         if (sock.connect("mbed.org", 80)) {
00040             printf("Socket connect timeout\n");
00041             continue;
00042         }
00043 
00044         // send command
00045         printf("Sending at %d seconds\n", time(NULL));
00046         char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt HTTP/1.0\n\n";
00047         sock.send_all(http_cmd, sizeof(http_cmd) - 1);
00048 
00049         // receive response
00050         int received = 0;
00051         int retries = 0;
00052         while (true) {
00053 
00054             int result;
00055             char buffer[256];
00056 
00057             result = sock.receive(buffer, sizeof(buffer) - 1);
00058             printf("Received: %d %d %d\n", result, received, retries);
00059 
00060             // if timeout or no data
00061             if (result <= 0) {
00062 
00063                 // if data previously received then stop receiving
00064                 if (received > 0)
00065                     break;
00066 
00067                 // if incremented retries exceeded then no response and stop receiving
00068                 if (++retries > RETRIES_ALLOWED) {
00069                     break;
00070                 }
00071 
00072             } else {
00073 
00074                 // zero terminate the buffer
00075                 buffer[result] = '\0';
00076 
00077                 // total size of data received
00078                 received += result;
00079             }
00080 
00081         }
00082 
00083         // close socket at end of send and receive
00084         sock.close();
00085         
00086         // wait before repeating
00087         Thread::wait(1000);
00088 
00089     }
00090 }