在ZeroMQ中,消息传递使用发布/订阅模式。发布者将消息发送到一个中间代理,然后订阅者从该代理接收消息。以下是在Python和C++中实现ZeroMQ发布/订阅模式的示例代码:
Python代码示例:
import zmq
# 创建上下文
context = zmq.Context()
# 创建发布者套接字
publisher = context.socket(zmq.PUB)
publisher.bind("tcp://*:5555")
# 发送消息
message = "Hello, World!"
publisher.send(message.encode())
# 关闭套接字和上下文
publisher.close()
context.term()
C++代码示例:
#include <zmqpp/zmqpp.hpp>
#include <string>
int main() {
// 创建上下文
zmqpp::context context;
// 创建发布者套接字
zmqpp::socket publisher(context, zmqpp::socket_type::pub);
publisher.bind("tcp://*:5555");
// 发送消息
std::string message = "Hello, World!";
publisher.send(message);
// 关闭套接字
publisher.close();
return 0;
}
以上的示例代码演示了如何在Python和C++中使用ZeroMQ来实现发布/订阅模式的消息传递。你可以根据自己的需求进行扩展和修改。