2
我嘗試使用ZeroMQ指南中的天氣示例,並使用epgm://
傳輸級別。起初,我的代碼:不要使用epgm://獲取消息,而使用tcp:// do。爲什麼?
// Publisher
#include "zhelpers.h"
int main (void) {
// Prepare our context and publisher
void *context = zmq_ctx_new();
void *publisher = zmq_socket (context, ZMQ_PUB);
// int rc = zmq_bind (publisher, "tcp://*:5556");
int rc = zmq_bind (publisher, "epgm://192.168.1.4;224.0.0.251:5556");
assert (rc == 0);
// Initialize random number generator
srandom ((unsigned) time (NULL));
while (1) {
// Get values that will fool the boss
int zipcode, temperature, relhumidity;
zipcode = randof (100000);
temperature = randof (215) - 80;
relhumidity = randof (50) + 10;
// Send a message to all subscribers
char update [20];
sprintf (update, "%05d %d %d", zipcode, temperature, relhumidity);
s_send (publisher, update);
}
zmq_close (publisher);
zmq_ctx_destroy (context);
return 0;
}
// Subscriber
#include "zhelpers.h"
int main (int argc, char *argv [])
{
// Socket to talk to server
printf ("Collecting updates from weather server…\n");
void *context = zmq_ctx_new();
void *subscriber = zmq_socket (context, ZMQ_SUB);
// int rc = zmq_connect (subscriber, "tcp://192.168.1.4:5556");
int rc = zmq_connect (subscriber, "epgm://192.168.1.9;224.0.0.251:5556");
assert (rc == 0);
// Subscribe to zipcode, default is NYC, 10001
char *filter = (argc > 1)? argv [1]: "10001 ";
rc = zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE,
filter, strlen (filter));
assert (rc == 0);
// Process 100 updates
int update_nbr;
long total_temp = 0;
for (update_nbr = 0; update_nbr < 100; update_nbr++) {
char *string = s_recv (subscriber);
int zipcode, temperature, relhumidity;
sscanf (string, "%d %d %d",
&zipcode, &temperature, &relhumidity);
total_temp += temperature;
free (string);
}
printf ("Average temperature for zipcode '%s' was %dF\n",
filter, (int) (total_temp/update_nbr));
zmq_close (subscriber);
zmq_ctx_destroy (context);
return 0;
}
- 我試過這個代碼
tcp://
在同一主機(見註釋),它工作正常。 - 我試了這個例子的組播地址Openbook Linux(用我的組播地址),我收到了這些消息。
- 我安裝ZeroMQ與
pgm://
(在我得到斷言故障之前)。 - 我的主機都是Ubuntu的16.04系統
- 我使用ZeroMQ 4
我的問題是,我不epgm://
得到任何消息。兩個程序都在運行,但沒有收到任何消息。我錯過了什麼?我不明白什麼是錯的。
您的代碼正在爲我工作。你是如何確認它沒有收到任何消息的? 嘗試將zipcode生成更改爲如下形式:'zipcode = randof(100)+ 9990;',1/100000命中100次可能需要一段時間才能獲得打印的內容。 在循環內添加打印件以查看它是否確實沒有收到任何東西。 –
對不起,我的遲到回覆。我在旅行。我再次嘗試,只有一個郵編,只有一個循環添加和它的工作。令我吃驚的是,因爲雙方都跑了一段時間,也許我在經過很長一段時間的測試之後開始犯了一個錯誤。 無論如何謝謝你的回答:-)。 – Runms