UDP Sockets use example

Dependencies:   EthernetNetIf mbed

UDPSocketExample.cpp

Committer:
donatien
Date:
2010-08-06
Revision:
0:5874b7a688d1

File content as of revision 0:5874b7a688d1:

#include "mbed.h"
#include "EthernetNetIf.h"
#include "UDPSocket.h"

EthernetNetIf eth;
UDPSocket udp;

void onUDPSocketEvent(UDPSocketEvent e)
{
  switch(e)
  {
  case UDPSOCKET_READABLE: //The only event for now
    char buf[64] = {0};
    Host host;
    while( int len = udp.recvfrom( buf, 63, &host ) )
    {
      if( len <= 0 )
        break;
      printf("From %d.%d.%d.%d: %s\n", host.getIp()[0], host.getIp()[1], host.getIp()[2], host.getIp()[3], buf);
    }
    break;
  }
}

int main() {
  printf("Setting up...\n");
  EthernetErr ethErr = eth.setup();
  if(ethErr)
  {
    printf("Error %d in setup.\n", ethErr);
    return -1;
  }
  printf("Setup OK\n");
  
  Host multicast(IpAddr(239, 192, 1, 100), 50000, NULL); //Join multicast group on port 50000
 
  udp.setOnEvent(&onUDPSocketEvent);
  
  udp.bind(multicast);
  
  Timer tmr;
  tmr.start();
  while(true)
  {
    Net::poll();
    if(tmr.read() > 5)
    {
      tmr.reset();
      const char* str = "Hello world!";
      udp.sendto( str, strlen(str), &multicast );
      printf("%s\n", str);
    }
  }

  
}