Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5119147
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2016-04-14 19:39:32


  1. import logging
  2. import zmq
  3.  
  4. class ZmqClient (object):
  5.  
  6.     def __init__(self, socket, logger):
  7.         super(ZmqClient, self).__init__()
  8.  
  9.         self._logger = logger
  10.         self._socket = socket
  11.         self._fd = socket.fd
  12.         self._callback = None
  13.         self._reactor = None
  14.  
  15.     def logPrefix(self):
  16.         """ Needed by twisted. """
  17.         return '.'.join([self.__class__.__name__, str(self.fileno())])
  18.  
  19.     def fileno(self):
  20.         """ Needed by twisted. """
  21.         return self._fd
  22.  
  23.     def __str__(self):
  24.         return self.logPrefix()
  25.  
  26.     def connectionLost(self, reason):
  27.         """ Needed by twisted. """
  28.         self._logger.info("{} unregistering from {}".format(self, self._reactor))
  29.         self._reactor.removeReader(self)
  30.         self._logger.warning("connection lost: {}".format(reason))
  31.  
  32.     def onReadable(self, callback):
  33.         self._callback = callback
  34.         return self
  35.  
  36.     def doRead(self):
  37.         while self._socket.events & zmq.POLLIN:
  38.             #print "D: {} invoking {} with {}".format(self, self._callback, self._socket)
  39.             self._callback(self._socket)
  40.  
  41.     def registerOn(self, reactor):
  42.         if not self._callback: raise Exception('callback is not set')
  43.  
  44.         self._logger.info("{} registered in {}".format(self, reactor))
  45.         self._reactor = reactor
  46.         self._reactor.addReader(self)
  47.         return self
  48.  
  49.  
  50. class Dumper:
  51.     def __init__(self, logger):
  52.         self._logger = logger
  53.          
  54.     def __call__(self, socket):
  55.         """ Invoked by Twisted reactor when data is readable on socket. """
  56.         data = socket.recv_multipart()
  57.         self._logger.info("data received: {}".format(data))
  58.  
  59.          
  60. if __name__ == "__main__":
  61.         ctx = zmq.Context()
  62.         socket = ctx.socket(zmq.SUB)
  63.         socket.bind("tcp://*:5563")
  64.         socket.subscribe = ""
  65.  
  66.     logging.basicConfig()
  67.         logger = logging.getLogger()
  68.  
  69.         dumper = Dumper(logger)
  70.  
  71.         from twisted.internet import reactor
  72.         zmq_client = ZmqClient(socket, logger) \
  73.                 .onReadable(dumper) \
  74.                 .registerOn(reactor)
  75.         reactor.run()

阅读(1550) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~