每一个zmq的套接字也可以认为是一路IO,那么在多路IO读写的时候,我们可以使用zmq_poll进行IO复用,使用了zmq_poll()函数,当收到了消息的第一帧时,其它帧其实也已经收到了。
订阅者代码如下:
static int interrupted = 0;
void signal_handler (int sig)
{
(void)sig;
interrupted = 1;
}
void catch_signals (void)
{
struct sigaction action;
action.sa_handler = signal_handler;
action.sa_flags = 0;
sigemptyset (&action.sa_mask);
sigaction (SIGINT, &action, NULL);
}
void dump_msg(const void * data, int size)
{
unsigned char * ptr = (unsigned char *)data;
printf ("[%03d] ", size);
int i = 0;
for (i = 0; i < size; i++)
printf ("%02X", ptr[i]);
printf ("\n");
}
int main (void)
{
catch_signals();
void *context = zmq_ctx_new();
void *subscriber = zmq_socket (context, ZMQ_SUB);
/*订阅任何内容*/
zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);
zmq_connect (subscriber, "tcp://127.0.0.1:5555");
int ret;
zmq_pollitem_t item[] = {{subscriber, 0, ZMQ_POLLIN, 0}};
while (!interrupted)
{
ret = zmq_poll(item, 1, -1);
if(ret == -1)
perror("zmq_poll");
if(item[0].revents & ZMQ_POLLIN)
{
zmq_msg_t msg;
zmq_msg_init(&msg);
ret = zmq_msg_recv (&msg, subscriber, 0);
dump_msg(zmq_msg_data(&msg), ret);
zmq_msg_close(&msg);
}
}
// 程序不会运行到这里,以下只是演示我们应该如何结束
zmq_close (subscriber);
zmq_ctx_destroy(context);
return 0;
}
以上代码使用zmq_poll来接受套接字信息,zmq_poll会被信号打断,并且不能自动重启,这里我们打印了一下中断错误信息,被中断后变量interrupted设为1, 退出循环。