zeromq学习记录(二)天气更新服务器使用ZMQ_SUB ZMQ_PUB

/**************************************************************
技术博客
http://www.cnblogs.com/itdef/
 
技术交流群
群号码:324164944
 
欢迎c c++ windows驱动爱好者 服务器程序员沟通交流
**************************************************************/
 
zeromq 指南里第二个例子是天气更新服务器
socket在代码中标记为ZMQ_SUB ZMQ_PUB
ZMQ_PUB 由发布者使用分发数据。
ZMQ_SUB 由订阅者来接受数据。需要使用setcockopt来设置订阅过滤器 否者接收不到任何内容
 
// wuserver_cpp.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
//
//  Weather update server in C++
//  Binds PUB socket to tcp://*:5556
//  Publishes random weather updates
//
//  Olivier Chamoux <olivier.chamoux@fr.thalesgroup.com>
//
//#include <zmq.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#if (defined (WIN32))
#include <zhelpers.hpp>
#endif

//#define within(num) (int) ((float) num * random () / (RAND_MAX + 1.0))

int main() {

    //  Prepare our context and publisher
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUB);
    publisher.bind("tcp://*:5556");
    //publisher.bind("ipc://weather.ipc");                // Not usable on Windows.

                                                        //  Initialize random number generator
    srandom((unsigned)time(NULL));
    while (1) {

        int zipcode, temperature, relhumidity;

        //  Get values that will fool the boss
        zipcode = within(100000);
        temperature = within(215) - 80;
        relhumidity = within(50) + 10;

        //  Send message to all subscribers
        zmq::message_t message(20);
        snprintf((char *)message.data(), 20,
            "%05d %d %d", zipcode, temperature, relhumidity);
        publisher.send(message);

    }
    return 0;
}
View Code
// wuclient_cpp.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <zmq.hpp>
#include <iostream>
#include <sstream>

int main(int argc, char *argv[])
{
    zmq::context_t context(1);

    //  Socket to talk to server
    std::cout << "Collecting updates from weather server…\n" << std::endl;
    zmq::socket_t subscriber(context, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5556");

    //  Subscribe to zipcode, default is NYC, 10001
    const char *filter = "";
    subscriber.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));

    //  Process 100 updates
    int update_nbr;
    long total_temp = 0;
    for (update_nbr = 0; update_nbr < 100; update_nbr++) {

        zmq::message_t update;
        int zipcode, temperature, relhumidity;

        subscriber.recv(&update);

        std::istringstream iss(static_cast<char*>(update.data()));
        iss >> zipcode >> temperature >> relhumidity;

        total_temp += temperature;
    }
    std::cout << "Average temperature for zipcode '" << filter
        << "' was " << (int)(total_temp / update_nbr) << "F"
        << std::endl;
    getchar();
    return 0;
}
View Code

 

posted on 2016-04-01 11:30  itdef  阅读(798)  评论(0编辑  收藏  举报

导航