Main Page | Modules | Class Hierarchy | Compound List | File List | Compound Members | File Members | Related Pages

Example on using the Mailer class

This page illustrates an example program which sends mail at a regular interval.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "RHexCom.hh"

#define MAILBOX_ID 100
struct MailStruct {
  int a, b;
  unsigned char c;
};

int main(int argc, char** argv)
{
  if (argc != 4) {
    fprintf(stderr, "Usage: mailer <port> <dest_machine> <dest_port>\n");
    exit(-1);
  }
  
  // create the communications manager
  unsigned short port = atoi(argv[1]);
  CommManager* mgr = new CommManager(port);
  
  // create the mailer to send to a remote communications manager
  Mailer* mailer = mgr->createMailer(argv[2], atoi(argv[3]),
                                     sizeof(MailStruct), MAILBOX_ID);
  for (int i=1;;i++) {
    Message* msg = mailer->createMsg(); // create the message

    // fill the message using the "direct" method
    MailStruct* ms = (MailStruct*) msg->getData();
    ms->a = i;
    ms->b = i*2;
    ms->c = i % 2;

    // send the message
    if (mailer->sendMsg(msg) < 0) {
      // this is probably paranoid, but illustrated the proper way to handle
      // a send error.  Send errors are more likely to happen with "exclusive"
      // mailboxes, which will become invalid if the destination manager dies 
      // and restarts.
      printf("Mailbox invalidated\n");
      mailer->releaseMsg(msg);
      break;
    }
    printf("Sent %d\n", i);
    usleep(1000000);
  }

  delete mgr;   // This is all we need for cleaning up
}

RHexLib Reference Documentation