ZMQ從入門到掌握三

2021-09-29 21:42:23 字數 1985 閱讀 1008

訂閱-發布模式

zeromq的訂閱發布模式是一種單向的資料發布,當客戶端向服務端訂閱訊息之後,服務端便會將產生的訊息源源不斷的推送給訂閱者

特點:1.乙個發布者,多個訂閱者的關係,1:n;

2.當發布者資料變化時發布資料,所有訂閱者均能夠接收到資料並處理。

這就是發布/訂閱模式。

注:使用sub設定乙個訂閱時,必須使用zmq_setsockopt()對訊息進行過濾,例如:

說明:發布者使用pub套接字將訊息傳送到佇列中,訂閱者使用sub套接字從佇列中源源不斷的接收訊息。新的訂閱者可以隨時加入,但之前的訊息是無法接收到的;已有的訂閱者可以隨時退出;訂閱者還可以新增「過濾器」用來有選擇性的接收訊息。

圖例:

案例**:

pub.cpp

#include #include #include #include #include #include "zmq.h"

int main()

; snprintf(szbuf, sizeof(szbuf), "server i=%d", i);

ret = zmq_send(socket, szbuf, strlen(szbuf) + 1, 0);

i++;

//sleep(1);

}zmq_close (socket);

zmq_ctx_destroy (context);

return 0;

}

sub.cpp

#include #include #include #include #include "zmq.h"

#include using namespace std;

#define true 1

void recv(void* arg)

; int ret = zmq_recv(socket, szbuf, sizeof(szbuf) - 1, 0);

if (ret > 0)

}}void recv2(void* arg)

; int ret = zmq_recv(socket, szbuf, sizeof(szbuf) - 1, 0);

if (ret > 0)

}}int main()

; ret = zmq_recv(socket, szbuf, sizeof(szbuf) - 1, 0);

if (ret > 0)

}*/ t1.join();

t2.join();

zmq_close(socket);

zmq_ctx_destroy(context);

return 0;

}

makefile

all:pub sub

cxx=g++

cxxflags=-fpic -std=c++11 -o

ldflags=-lzmq -lpthread

pub:pub.cpp

$(cxx) pub.cpp $(cxxflags) pub $(ldflags)

sub:sub.cpp

$(cxx) sub.cpp $(cxxflags) sub $(ldflags)

clean:

rm -f sub pub

dflags)

sub:sub.cpp

$(cxx) sub.cpp $(cxxflags) sub $(ldflags)

clean:

rm -f sub pub

***********

*****

ZMQ從入門到掌握二

原始碼走讀 1.zmq ctx new 返回ctx t物件 void zmq ctx new void create 0mq context.zmq ctx t ctx new std nothrow zmq ctx t if ctx return ctx 函式返回context 上下文 其實呼叫的...

從入門到實踐,快速掌握 Nginx 研發

對於開發來說,我們在工作中或多或少都會遇到 web 效能優化 高併發等問題,而 nginx 是乙個萬能藥,它具備高效能 高擴充套件性 高可靠性 低記憶體消耗等優勢,不管是個人建立 部落格,還是進行網際網路應用開發,都可以輕鬆應對。實驗樓上線了一門 nginx 網路模組編寫入門 課程,或許可以幫助到有...

Python 從入門到放棄(三)

2011 12 11 mon 13 58 直接建立 phonebook phonebook out 224 phonebook dict alice 1234 bob 2345 注意關鍵字不能是expression,不是 alice 而是alice phonebook out 228 或者通過鍵值對...