Test network communications

Dependencies:   EthernetInterface mbed-rtos mbed

Files at this revision

API Documentation at this revision

Comitter:
MalcolmNixon
Date:
Sun May 04 02:39:28 2014 +0000
Parent:
0:9eba2bd74769
Child:
2:d62b28f02d45
Commit message:
Removed threads and just switched to a TCP server on port 1234

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/main.cpp	Sun May 04 02:09:14 2014 +0000
+++ b/main.cpp	Sun May 04 02:39:28 2014 +0000
@@ -3,57 +3,48 @@
 #include "mbed.h"
 
 
-
-// Construct the Ethernet interface
-EthernetInterface eth;
-    
-// Led thread procedure
-void ledThreadProc(const void *)
+int main(void)
 {
-    // Create a digital output pin on LED1 (the Red LED)
+    // Create a digital output on LED1
     DigitalOut led1(LED1);
     
-    // Loop forever
+    // Construct the Ethernet interface
+    EthernetInterface eth;
+    eth.init("192.168.5.100", "255.255.255.0", "0.0.0.0");
+    eth.connect();
+
+    // Construct the server
+    TCPSocketServer svr;
+    svr.bind(1234);
+    svr.listen();
     for (;;)
     {
-        // Turn LED off
-        led1 = 1;
-        
-        // Wait for 100ms
-        Thread::wait(100);
-        
-        // Turn LED on
-        led1 = 0;
-        
-        // Wait for 100ms
-        Thread::wait(100);
-    }
-}
-
-int main(void)
-{
-    // Configure the Ethernet interface
-    eth.init("192.168.5.100", "255.255.255.0", "0.0.0.0");
-    
-    // Start the ethernet interface
-    eth.connect();
-    
-    // Start a thread for led blink
-    Thread ledThread(ledThreadProc, 0, osPriorityHigh);
-
-    UDPSocket sock;
-    sock.init();
-    
-    Endpoint ep;
-    ep.set_address("192.168.5.1", 1234);
-        
-    // Loop forever
-    for (;;)
-    {
-        char msg[] = "Hello World";
-        sock.sendTo(ep, msg, sizeof(msg) - 1);
-        
-        // Wait 1 second
-        Thread::wait(1000);
-    }
+        // Accept the next connection
+        TCPSocketConnection conn;
+        if (svr.accept(conn) == 0)
+        {
+            // Turn the TCP_NODELAY option on
+            int opt = 1;
+            conn.set_option(IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt));
+            
+            // Manage the connection
+            for (;;)
+            {
+                // Read the input
+                char buf[128];
+                int nr = conn.receive(buf, 128);
+                if (nr <= 0)
+                {
+                    break;
+                }
+                
+                // Toggle the output on led1
+                led1 = !led1;
+                
+                // Write the response twice
+                conn.send(buf, nr);
+                conn.send(buf, nr);
+            }
+        }
+    }    
 }
\ No newline at end of file