python/sub/pub/rep/req

[root@han node]# cat pubrepnode.py 
import zmq
import time

a = 0

def rep(node):
    global a
    print('------------')
    time.sleep(1)
    a = a+1
    node.pub_socket.send_string("%s %s" % ('onu/online', str(a)))

class PubRepNode(object):
    def __init__(self, publish_address, reply_address):
        self.context = zmq.Context()
        self.pub_socket = self.context.socket(zmq.PUB)
        self.pub_socket.bind(publish_address)
        self.rep_socket = self.context.socket(zmq.REP)
        self.rep_socket.bind(reply_address)
    
    def publish(self, topic, content):
        self.pub_socket.send_string("%i %s" % (topic, content))

    def start(self, rep_func):
        while True:
            rep_func(self)

    def publish(self, topic, data):
        pass
        #socket.send_json("%i %i %i" % ('onu/online/001122334455', data))

node = PubRepNode("tcp://*:55566", "tcp://*:55567")
node.start(rep)

[root@han node]# cat subreqnode.py 
import zmq
import time

def subscribe_callback(node):
    string = node.sub_socket.recv_string()
    print('{}'.format(string))


class SubReqNode(object):
    def __init__(self, subscribe_address, request_address):
        self.context = zmq.Context()
        self.sub_socket = self.context.socket(zmq.SUB)
        self.sub_socket.connect(subscribe_address)
        self.req_socket = self.context.socket(zmq.REQ)
        self.req_socket.connect(request_address)
    
    def send_req(self, topic, content):
        self.pub_socket.send_string("%i %s" % (topic, content))

    def start(self, subsribe_callback):
        while True:
            subscribe_callback(self)

    def subscribe(self, topic):
        zip_filter = topic
        zip_filter = zip_filter.decode('ascii')
        self.sub_socket.setsockopt_string(zmq.SUBSCRIBE, zip_filter)
        pass

node = SubReqNode("tcp://127.0.0.1:55566", "tcp://127.0.0.1:55567")
node.subscribe('onu/online')
node.start(subscribe_callback)

[root@han node]# 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值