ZMQ從入門到掌握<四>
推拉模式
推拉模式,PUSH發送,send。PULL方接收,recv。PUSH可以和多個PULL建立連接,PUSH發送的數據被順序發送給PULL方。比如你PUSH和三個PULL建立連接,分別是A,B,C。PUSH發送的第一數據會給A,第二數據會給B,第三個數據給C,第四個數據給A。一直這麼循環。
看一下圖:
- 最上面是產生任務的 分發者 ventilator
- 中間是執行者 worker
- 下面是收集結果的接收者 sink
代碼:
Ventilator.cpp
#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
void * context = zmq_ctx_new();
void * sender = zmq_socket(context, ZMQ_PUSH);
zmq_bind(sender, "tcp://*:6666");
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 <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
int main(void)
{
void * context = zmq_ctx_new();
void * recviver = zmq_socket(context, ZMQ_PULL);
zmq_connect(recviver, "tcp://localhost:6666");
void * sender = zmq_socket(context, ZMQ_PUSH);
zmq_connect(sender, "tcp://localhost:5555");
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 <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
int main(void)
{
void * context = zmq_ctx_new();
void * socket = zmq_socket(context, ZMQ_PULL);
zmq_bind(socket, "tcp://*:5555");
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;
}
想了解學習更多C++後臺服務器方面的知識,請關注:
微信公衆號:C++後臺服務器開發
zmq_ctx_destroy(context);
return 0;
}
*******
想了解學習更多C++後臺服務器方面的知識,請關注:
微信公衆號:====**C++後臺服務器開發**====
******