Reputation: 3927
My class MasterSlaveSynchronize is used both to send and recived hearbeat. Is it ok to have only one datagram socket that will use to both - send , recieved ?
The 2 method bellow run from time to time and can run simultaneously.
void MasterSlaveSynchronize::sendHearBeat() {
const int HEARBEAT_LEN = 1;
const char HEARBEAT[1] = { '1' };
int n = sendto(sock, HEARBEAT, HEARBEAT_LEN, 0,(const struct sockaddr *) &target_, length_);
if (n < 0)
printf("Sendto"); //TODO ERR
}
void MasterSlaveSynchronize::recivedHearBeat() {
char buf[1024];
if (bind(sock, (struct sockaddr *) &this_, length_) < 0)
printf("binding"); //TODO err
while (1) {
int n = recvfrom(sock, buf, 1024, 0, (struct sockaddr *) &target_,&length_);
if (n < 0)
printf("recvfrom"); //TODO ER
//TODO update got hearbeat
}
Upvotes: 2
Views: 711
Reputation: 339906
Yes, it's fine (indeed expected) to use the same socket for sendto
and recvfrom
.
However your recivedHearBeat()
function never exits. That's OK, if it's running in a separate thread.
Upvotes: 2