下载ZMQ模块
pip install pyzmq
创建一个 SUB 套接字来监听消息
import zmq
def main():
# 创建 ZeroMQ 上下文对象
context = zmq.Context()
# 创建 SUB 套接字,并连接到发布者端点
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:5555")
# 设置订阅主题(这里订阅所有主题)
socket.setsockopt_string(zmq.SUBSCRIBE, "")
try:
# 循环接收消息并打印出来
while True:
message = socket.recv_string()
print(f"Received message: {message}")
except KeyboardInterrupt:
print("Interrupted, closing the application.")
finally:
# 关闭套接字和上下文
socket.close()
context.term()
if __name__ == "__main__":
main()