I am using zeromq and trying to do a pub/sub socket. I found examples of how to transfer char* , but I need to know how to transfer a vector from the server, and how to receive it on the client. I already have a vector<mystruct> filled with data. and the transfer of char is organized, but I do not understand how to transfer and receive a vector<mystruct>.
I tried to do it like this, at the client:
vector<students> inMsg(zmq_msg_size(&reply));
memcpy(inMsg.data(), zmq_msg_data(&reply), zmq_msg_size(&reply));
And like this, at the server, but it doesn't work:
zmq_msg_t message;
zmq_msg_init_data(&message, &vectorData, sizeof(&vectorData), nullptr, NULL);
zmq_msg_send(&message, publisher, 0);
zmq_msg_close(&message);
I would be very grateful for any hints. p.s. Sorry for bad English.
Here is a working example with char. Server-side:
int main(int argc, char const *argv[])
{
void* context = zmq_ctx_new();
void* publisher = zmq_socket(context, ZMQ_PUB);
printf("Starting server\n");
int conn = zmq_bind(publisher, "tcp://127.0.0.1:8080");
const char* companies[2] = { "Company1", "Company2" };
int count = 0;
for (;;)
{
int price = count % 2;
int which_company = count % 2;
int index = strlen(companies[0]);
char update[12];
snprintf(update, sizeof update, "%s",
companies[which_company]);
Sleep(3000);
zmq_msg_t message;
zmq_msg_init_size(&message, index);
memcpy(zmq_msg_data(&message), update, index);
zmq_msg_send(&message, publisher, 0);
zmq_msg_close(&message);
count++;
}
zmq_close(publisher);
zmq_ctx_destroy(context);
return 0;
}
Client-side:
int main(int argc, char const *argv[])
{
void* context = zmq_ctx_new();
void* subscriber = zmq_socket(context, ZMQ_SUB);
printf("Collecting stock information from the server.\n");
int conn = zmq_connect(subscriber, "tcp://127.0.0.1:8080");
conn = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, 0, 0);
for (int i = 0; i < 10; i++)
{
zmq_msg_t reply;
zmq_msg_init(&reply);
zmq_msg_recv(&reply, subscriber, 0);
int length = zmq_msg_size(&reply);
char* value = (char*)malloc(length*sizeof(char)); //
memcpy(value, zmq_msg_data(&reply), length);
zmq_msg_close(&reply);
printf("%s\n", value);
free(value);
}
zmq_close(subscriber);
zmq_ctx_destroy(context);
return 0;
}