SOL9 Sample: SocketDatagramReceiver

SOL9 2.0 Samples

1 Screenshot


2 Source code

/*
 * SocketDatagramReceiver.cpp 
 * Copyright (c) 2015 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */



#include <sol/SocketDatagram.h>


class  SocketDatagramReceiver {
  SocketDatagram socketDatagram;

public:
  SocketDatagramReceiver()
  {
  }

public:
  ~SocketDatagramReceiver()
  {
    socketDatagram.close();
  }


public:
  void recv(unsigned short port) {

    bool looping = true;
    while (looping) {
      char buf[SIZE_1KB];
      try {
        //1 Receive a string.
        //Blocked, waiting infinitely to recv data.
        int rc = socketDatagram.recvFrom(port, buf, sizeof(buf));
        if (rc >0) {
          printf("recv: string=[%s] len=%d(bytes)\n", 
            buf, rc);
          //2 ReplyBack to a sender 
          const char* ok= "OK. Got a datagram.";
          int r = socketDatagram.replyTo(ok, strlen(ok));
          if (r >0) {
            printf("sent:%s\n", ok);
          }
        }
        if (rc <=0) {
          printf("Exit loop\n");
          break;
        }
      } catch (Exception& ex) {
        ex.printf();
      } catch (...) {

      }
      
    }
  }
};


/**
 *
 */
int main(int argc, char* argv[])
{
  try {
    printf("Create SocketDatagramReceiver\n");

    //Recv data from port=32000
    SocketDatagramReceiver receiver;

    receiver.recv(32000);

  } catch (Exception& ex) {
    ex.printf();

  } catch (...) {
    printf("Exception\n");
  }

  return 0;
}

Last modified: 2 May 2016

Copyright (c) 2016 Antillia.com ALL RIGHTS RESERVED.