ZeroMQ---推拉模式

概述

推拉模式,PUSH发送,send。PULL方接收,recv。PUSH可以和多个PULL建立连接,PUSH发送的数据被顺序发送给PULL方。比如你PUSH和三个PULL建立连接,分别是A,B,C。PUSH发送的第一数据会给A,第二数据会给B,第三个数据给C,第四个数据给A。一直这么循环。

推拉模式可分为三层,最上是产生任务的 分发者 ventilator,中间是执行者 worker,下面是收集结果的接收者 sink。

代码

Ventilator.cpp

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(void)
{
    void * context = zmq_ctx_new();
    void * sender = zmq_socket(context, ZMQ_PUSH); // 
    zmq_bind(sender, "tcp://*:8080");
    
	printf ("Press Enter when the workers are ready: ");
    getchar ();    
	printf ("Sending tasks to workers...\n");
	
    while(1)
    { 
        const char * replyMsg = "World";
        zmq_send(sender, replyMsg, strlen(replyMsg), 0);
        printf("[Server] Sended Reply Message content == \"%s\"\n", replyMsg);
    }    
    zmq_close(sender);
    zmq_ctx_destroy(context);
    
    return 0;
}

work.cpp

#include 
#include 
#include 
#include 
#include 

int main(void)
{
    void * context = zmq_ctx_new();
    void * recviver = zmq_socket(context, ZMQ_PULL); // 
    zmq_connect(recviver, "tcp://localhost:8080");
    
	void * sender = zmq_socket(context, ZMQ_PUSH); //
    zmq_connect(sender, "tcp://localhost:9000");

    while(1)
    { 
		char buffer [256];
		int size = zmq_recv (recviver, buffer, 255, 0); //
		if(size < 0)
		{
			return -1;
		}
        printf("buffer:%s\n",buffer);
        const char * replyMsg = "World";
        zmq_send(sender, replyMsg, strlen(replyMsg), 0); //
        printf("[Server] Sended Reply Message content == \"%s\"\n", replyMsg);
    }

    zmq_close(recviver);
	zmq_close(sender);
    zmq_ctx_destroy(context);

    return 0;
}
sink.cpp
#include 
#include 
#include 
#include 
#include 

int main(void)
{
    void * context = zmq_ctx_new();
    void * socket = zmq_socket(context, ZMQ_PULL);
    zmq_bind(socket, "tcp://*:9000");

    while(1)
    { 
       char buffer [256];
		int size = zmq_recv (socket, buffer, 255, 0);
		if(size < 0)
		{
			return -1;
		}
        printf("buffer:%s\n",buffer);
    }
    zmq_close(socket);
    zmq_ctx_destroy(context);
    return 0;
}

你可能感兴趣的:(cpp)