Skip to content

Instantly share code, notes, and snippets.

@Mystfit
Last active July 15, 2024 10:55
Show Gist options
  • Select an option

  • Save Mystfit/6c015257b637ae31bcb63130da67627c to your computer and use it in GitHub Desktop.

Select an option

Save Mystfit/6c015257b637ae31bcb63130da67627c to your computer and use it in GitHub Desktop.
libzmq Radio/Dish example using UDP multicast
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h> // for usleep
#define ZMQ_BUILD_DRAFT_API
#include <zmq.h>
volatile sig_atomic_t stop;
const char *mcast_url = "udp://239.0.0.1:40000";
const char *unicast_url = "udp://127.0.0.1:40000";
void inthand(int signum) {
stop = 1;
}
void my_free (void *data, void *hint)
{
free (data);
}
#include "test_radio_dish_udp.h"
int main(int argc, char *argv[])
{
void *ctx = zmq_ctx_new();
void *dish = zmq_socket(ctx, ZMQ_DISH);
const char* url = NULL;
if(argc > 1){
if(argv[0] == 'm'){
url = mcast_url;
} else {
url = unicast_url;
}
}
printf( "Binding dish\n" );
int rc = zmq_bind(dish, url);
assert(rc > -1);
const char* group = "mcast_test";
printf( "Dish joining group\n" );
zmq_join(dish, group);
signal(SIGINT, inthand);
printf( "Waiting for dish message\n" );
while (!stop){
zmq_msg_t recv_msg;
zmq_msg_init (&recv_msg);
zmq_recvmsg (dish, &recv_msg, 0);
printf("%s", (char*)zmq_msg_data(&recv_msg));
printf( "\n" );
zmq_msg_close (&recv_msg);
}
printf( "Closing");
zmq_close(dish);
zmq_ctx_term(ctx);
return 0;
}
#include "test_radio_dish_udp.h"
int main(int argc, char *argv[])
{
void *ctx = zmq_ctx_new();
void *radio = zmq_socket(ctx, ZMQ_RADIO);
char* url = NULL;
if(argc > 1){
if(argv[0] == 'm'){
url = mcast_url;
} else {
url = unicast_url;
}
}
printf( "Connecting radio\n" );
int rc = zmq_connect(radio, url);
assert(rc > -1);
const char* group = "mcast_test";
signal(SIGINT, inthand);
int message_num = 0;
while (!stop){
void *data = malloc(255);
memset(data, 0, sizeof(data));
sprintf(data, "%d", message_num);
zmq_msg_t msg;
zmq_msg_init_data (&msg, data, 255, my_free, NULL);
zmq_msg_set_group(&msg, group);
printf( "Sending message %d\n", message_num);
zmq_sendmsg(radio, &msg, 0);
message_num++;
usleep(100);
}
printf( "Closing");
zmq_close(radio);
zmq_ctx_term(ctx);
return 0;
}
@Mystfit
Copy link
Author

Mystfit commented Mar 25, 2022

I just checked the order of my my radio/dish UDP sockets in another project and I'm using connect on my radio and no bind on my dish with multicast addresses. Not sure why they're revered but maybe its to do with using UDP specifically which is one way?

@Durant35
Copy link

Very thanks a lot, I also found this strange... BTW, have you ever try cppzmq using udp? as mentioned in zeromq/cppzmq#549

@Mystfit
Copy link
Author

Mystfit commented Mar 27, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment