#include #include #include #include #include #include #include #include #include #include "MKControl.h" #include "MKCommModel.h" using namespace std; MKControl::MKControl(MKCommModel *mod) { this->model = mod; } MKControl::~MKControl() { pthread_cancel(thread); pthread_join(thread, NULL); } MKControl *MKControl::start(MKCommModel *model) { MKControl *instance = new MKControl(model); pthread_create(&instance->thread, NULL, MKControl::initThread, instance); return instance; } void *MKControl::initThread(void *control) { (reinterpret_cast(control))->begin(); return NULL; } void MKControl::begin() { struct sockaddr_in addr; int fd, nbytes; socklen_t addrlen; struct ip_mreq mreq; char msgbuf[kMsgBufSize]; char *data; mongo::BSONObj *bData; int x = 1; /* create what looks like an ordinary UDP socket */ if ((fd=socket(AF_INET,SOCK_DGRAM,0)) < 0) { perror("socket"); exit(1); } /* set up receive address */ memset(&addr,0,sizeof(addr)); addr.sin_family=AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port=htons(MK_CC_PORT); if(setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&x,sizeof(x)) < 0) { perror("setsockopt1"); exit(1); } /* bind to receive address */ if(bind(fd,(struct sockaddr *) &addr,sizeof(addr)) < 0) { perror("bind"); exit(1); } /* use setsockopt() to request that the kernel join a multicast group */ mreq.imr_interface.s_addr=htonl(INADDR_ANY); /* now just enter a read-print loop */ while (1) { addrlen=sizeof(addr); if ((nbytes = recvfrom(fd, msgbuf, kMsgBufSize, 0, (struct sockaddr *) &addr, &addrlen)) < 0) { perror("recvfrom"); exit(1); } else { int reqID = 0; string idStr; bData = new mongo::BSONObj(msgbuf, false); reqID = bData->getField("id").numberInt(); // reqID = atoi(idStr.c_str()); MKRequest *req = MKRequest::cache(reqID); if(req == NULL) { MKCommModel::log() << "Ignoring expired cc response id #" << reqID << endl; } else { model->update(bData, req); //addr.sin_addr.s_addr); } delete bData; } } }