[c++] ZeroMQ 단방향 통신

ZeroMQ는 메시지 지향 미들웨어 라이브러리로서 다양한 프로그래밍 언어에서 사용할 수 있습니다. 이 라이브러리를 사용하여 C++ 언어로 간단한 단방향 통신을 구현하는 방법을 알아보겠습니다.

ZeroMQ 및 C++ 환경 설정

먼저, ZeroMQ 라이브러리를 설치하고 C++ 프로젝트에 라이브러리를 링크하기 위해 적절한 환경 설정이 필요합니다.

# ZeroMQ 라이브러리 설치
$ sudo apt-get install libzmq3-dev

C++ 프로젝트에서는 다음과 같이 라이브러리를 링크합니다.

find_package(PkgConfig)
pkg_search_module(ZMQ REQUIRED libzmq)

target_link_libraries(your_target_name ${ZMQ_LIBRARIES})

Publisher-Subscriber 모델

이번 예제에서는 ZeroMQ의 Publisher-Subscriber 모델을 사용하여 단방향 통신을 구현합니다. Publisher는 메시지를 보내는 역할을 수행하고, Subscriber는 이를 수신합니다.

Publisher (발행자) 구현

#include <zmq.hpp>
#include <string>
#include <iostream>

int main() {
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUB);
    publisher.bind("tcp://*:5556");

    while (true) {
        std::string message = "Hello, World!";
        publisher.send(zmq::message_t(message.c_str(), message.size()), zmq::send_flags::none);
    }
    return 0;
}

Subscriber (구독자) 구현

#include <zmq.hpp>
#include <string>
#include <iostream>

int main() {
    zmq::context_t context(1);
    zmq::socket_t subscriber(context, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5556");
    subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);

    while (true) {
        zmq::message_t update;
        subscriber.recv(update);
        std::string message = std::string(static_cast<char*>(update.data()), update.size());
        std::cout << "Received: " << message << std::endl;
    }
    return 0;
}

실행

다음과 같이 Publisher와 Subscriber를 각각 빌드하고 실행합니다.

$ g++ publisher.cpp -o publisher -lzmq
$ g++ subscriber.cpp -o subscriber -lzmq
$ ./publisher
$ ./subscriber

위와 같이 간단한 코드로 ZeroMQ 라이브러리를 사용하여 C++에서의 단방향 통신을 구현할 수 있습니다.

참고 자료