当在{send()`

时间:2018-11-13 18:33:04

标签: python zeromq publish-subscribe pyzmq

我要达到什么目的?

使用zmq进行可靠的PUB / SUB,订阅者可以根据自己的意愿来来去去。

而且,或多或少地模拟这种模式。

enter image description here

我知道这个问题以前曾被问过。

我的不同之处在于以下代码-

  • 使用ROUTER-DEALER进行显式同步,以避免慢联接综合症。
  • Context之后不会立即关闭Socket / send()

    import zmq
    import time
    import multiprocessing
    from pathlib import Path
    
    ADDR = f"ipc://{Path.home()}/.tmp/pubsubtest"
    ADDR2 = f"ipc://{Path.home()}/.tmp/pairtest"
    
    
    def server():
        with zmq.Context() as ctx, \
                ctx.socket(zmq.PUB) as pub, \
                ctx.socket(zmq.ROUTER) as router:
    
            pub.bind(ADDR)
            router.bind(ADDR2)
    
            i = 0
            while True:
                router.send_multipart(router.recv_multipart())
                pub.send_pyobj(i)
    
                # Client's don't recv anything without this!
                time.sleep(0.1)                  
    
                print("sent:", i)
    
                i += 1
    
    
    
    def client():
        with zmq.Context() as ctx, \
                ctx.socket(zmq.SUB) as sub, \
                ctx.socket(zmq.DEALER) as dealer:
    
            sub.setsockopt(zmq.SUBSCRIBE, b"")
            sub.connect(ADDR)                
            dealer.connect(ADDR2)                
    
            dealer.send(b"")
            dealer.recv()
    
            print("recv:", sub.recv_pyobj())
    
    
    def simulator():
        p = multiprocessing.Process(target=server)
        try:
            p.start()    
            while True:
                client()
        finally:
            p.terminate()
            p.join()
    
    simulator()
    

0 个答案:

没有答案