python/zeromq/IOLoop

直接用tornado中的IOLoop代替zmq.eventloop.ioloop

# coding: utf-8

import os
import zmq
import tornado
# from zmq.eventloop.ioloop import IOLoop
from tornado.ioloop import IOLoop
from zmq.eventloop.zmqstream import ZMQStream

# 分类后的日志的zmq的pub地址
LOG_TYPE_PUB_PATH = "tcp://127.0.0.1:5601"

# simulator 日志的zmq的sub地址
LOG_SUB_PATH = "tcp://127.0.0.1:5602"
TOPIC_LIST = ["lator", "att"]


def recv_func(msg):
    print(msg)


def main2():
    loop_instance = IOLoop.instance()
    ctx = zmq.Context.instance()
    sock = ctx.socket(zmq.SUB)
    sock.set_hwm(100)
    sock.connect(LOG_TYPE_PUB_PATH)
    sock.connect(LOG_SUB_PATH)
    for key in TOPIC_LIST:
        sock.setsockopt_string(zmq.SUBSCRIBE, key)
        print("log_broker to set subscribe error:%s" % key)
    sock = ZMQStream(sock, loop_instance)
    sock.on_recv(recv_func)
    loop_instance.start()


if __name__ == "__main__":
    main2()
# coding: utf-8

import zmq
import time
import threading
import os
import stat

# 分类后的日志的zmq的pub地址
LOG_TYPE_PUB_PATH = "tcp://127.0.0.1:5601"

# simulator 日志的zmq的sub地址
LOG_SUB_PATH = "tcp://127.0.0.1:5602"
TOPIC_LIST = ["lator", "att"]


def pub(pubaddr, topic):
    context = zmq.Context()
    sock = context.socket(zmq.PUB)
    sock.set_hwm(100)
    sock.bind(pubaddr)
    counter = 1
    zpath = sock.getsockopt(zmq.LAST_ENDPOINT)
    print(zpath)

    while True:
        messagedata = "this is msg fro topic one %s" % counter
        print("%s %s" % (topic, messagedata))
        sock.send_string("%s %s" % (topic, messagedata))
        counter = counter + 1
        time.sleep(1)


if __name__ == "__main__":
    t1 = threading.Thread(target=pub, args=(LOG_TYPE_PUB_PATH, "lator"))
    t2 = threading.Thread(target=pub, args=(LOG_SUB_PATH, "att"))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

你可能感兴趣的:(ATE,python,zeromq)