Simple code for comunication via TCP between the mbed and PC.

Dependencies:   EthernetInterface SimpleSocket mbed-rtos mbed

Fork of SimpleSocketExamples by Hiroshi Yamaguchi

examples/findbuddy.cpp

Committer:
numeral369
Date:
2014-12-17
Revision:
1:016774025718
Parent:
0:6dc3cfd058c6

File content as of revision 1:016774025718:

#include "SimpleSocket.h"

void findbuddy()
{
    int myIP[4];
    sscanf(EthernetInterface::getIPAddress(), "%d.%d.%d.%d", myIP, myIP + 1, myIP + 2, myIP + 3);

    DatagramSocket datagram(7777);

    char buddy[32] = {};
    int port;
    for (int i = myIP[3] + 1;; i = (i - myIP[3] + 260) % 10 + myIP[3] + 1) {
        sprintf(buddy, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], i);
        printf("sending message to %s\n", buddy);
        datagram.printf("Hello World\n");

        datagram.send(buddy, 7777);
        // this will not reach target during the first round,
        // and in order to receive successfully,
        // timeout must be at least 4 seconds (default = 5.0 seconds)
        datagram.setTimeout(4.0);
        if (datagram.receive(buddy, &port) > 0) {
            char buf[80] = {};
            int len = datagram.read(buf, sizeof(buf) - 1);
            printf("received from %s: %s", buddy, buf);
            break;
        }
    }

    for (int i = 0; i < 2; i++) {
        datagram.printf("There you are!\n");
        datagram.send(buddy, 7777);

        if (datagram.receive() > 0) {
            char buf[80] = {};
            int len = datagram.read(buf, sizeof(buf) - 1);
            printf("received: %s", buf);
        }
    }
}