2017-01-30 89 views
3

我的(Python)的出版商:爲什麼我的C++ ZeroMQ訂戶沒有收到任何數據?

import zmq 
import time 

context = zmq.Context() 
socket = context.socket(zmq.PUB) 
connectStr = "tcp://*:%d" % 5563 
socket.bind(connectStr) 

messageNum = 0 
while True: 
    ++messageNum 
    message = "Testing %d"%messageNum 
    print("Sending.. '%s'"%message) 
    socket.send_string(message) 
    time.sleep(1) 
    messageNum += 1 

我的(C++)的用戶(在GTEST運行):

TEST(ZeroMqPubSubTest, SubscribeGetsData) 
{ 

    // Set up the subscriber we'll use to receive the message. 
    zmq::context_t context; 
    zmq::socket_t subscriber(context, ZMQ_SUB); 
    // Connect to the publisher 
    subscriber.connect("tcp://127.0.0.1:5563"); 
    subscriber.setsockopt(ZMQ_SUBSCRIBE, ""); // Set the filter blank so we receive everything 

    zmq::message_t response(0); 
    EXPECT_TRUE(subscriber.recv(&response)); 
} 

我開始了出版商然後啓動用戶。後者永遠不會回來。

如果我運行一個Python用戶做的(我認爲)完全一樣的東西..

import zmq 

context = zmq.Context() 
socket = context.socket(zmq.SUB) 
socket.connect ("tcp://127.0.0.1:5563") 
socket.setsockopt_string(zmq.SUBSCRIBE, "") 

print ("Waiting for data...") 
while True: 
    message = socket.recv() 
    print ("Got some data:",message) 

..它工作正常:

等待數據...

得到一些數據:b'Testing 8'

得到一些數據:b'Testing 9'

回答

2

有很多setsockopt兩個重載在zmq.hpp定義:

template<typename T> void setsockopt(int option_, T const& optval) 
{ 
    setsockopt(option_, &optval, sizeof(T)); 
} 

inline void setsockopt (int option_, const void *optval_, size_t optvallen_) 
{ 
    int rc = zmq_setsockopt (ptr, option_, optval_, optvallen_); 
    if (rc != 0) 
     throw error_t(); 
} 

通過僅提供兩個參數你含蓄使用的第一過載,其假設的sizeof(T)的值的長度。這解決爲1,因爲""是零終止的字符數組。通過在一個空字符串需要使用所述第二過載,並指定的長度爲0:

subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); 

或者,使用一個零大小的數據類型:

char none[0]; 
subscriber.setsockopt(ZMQ_SUBSCRIBE, none); 
+0

點上@kazemakase。我仍然在學習ZeroMQ的精妙之處,看起來特別是cpp接口的幾個方面有幾個問題。 –

相關問題