Threads + Network Demo

Dependencies:   EthernetInterface mbed-rtos mbed-src

Fork of TestNetComm by Malcolm Nixon

main.cpp

Committer:
MalcolmNixon
Date:
2014-05-04
Revision:
3:1e86c29d1eac
Parent:
2:d62b28f02d45
Child:
4:f2789e665f4e

File content as of revision 3:1e86c29d1eac:

#include "EthernetInterface.h"
#include "Thread.h"
#include "mbed.h"

DigitalOut led2(LED2, 1);
    
// Blink function
void blink(const void *param)
{
    led2 = !led2;
}

int main(void)
{
    // Create a digital output on LED1
    DigitalOut led1(LED1, 1);

    // Start the blink timer at 1 second interval
    RtosTimer timer(blink);
    timer.start(1000);
    
    // 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 (;;)
    {
        // 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);
            }
        }
    }    
}