spacepaste

  1.  
  2. #!/usr/bin/env python
  3. import traceback
  4. import sys
  5. import zmq
  6. from time import sleep
  7. context = zmq.Context()
  8. context2 = zmq.Context()
  9. sender = context.socket(zmq.PUB)
  10. sender.bind("tcp://*:5557")
  11. receiver = context2.socket(zmq.SUB)
  12. receiver.connect("tcp://localhost:5557")
  13. receiver.setsockopt(zmq.SUBSCRIBE, "B")
  14. for i in range(1,10):
  15. msg = "msg %d" % (i)
  16. env = None
  17. if i % 2 == 0:
  18. env = ["B", msg]
  19. else:
  20. env = ["A", msg]
  21. print "Send Message: ", env
  22. sender.send_multipart(env)
  23. sender.close()
  24. timeout = 0
  25. while timeout < 10:
  26. try:
  27. print receiver.recv_multipart(zmq.NOBLOCK)
  28. except:
  29. print traceback.format_exception(*sys.exc_info())
  30. timeout += 1
  31. sleep(2)
  32. """
  33. Output:
  34. Send Message: ['A', 'msg 1']
  35. Send Message: ['B', 'msg 2']
  36. Send Message: ['A', 'msg 3']
  37. Send Message: ['B', 'msg 4']
  38. Send Message: ['A', 'msg 5']
  39. Send Message: ['B', 'msg 6']
  40. Send Message: ['A', 'msg 7']
  41. Send Message: ['B', 'msg 8']
  42. Send Message: ['A', 'msg 9']
  43. ['Traceback (most recent call last):\n', ' File "./test.py", line 33, in <module>\n print receiver.recv_multipart(zmq.NOBLOCK)\n', ' File "socket.pyx", line 611, in zmq.core.socket.Socket.recv_multipart (zmq/core/socket.c:5181)\n', ' File "socket.pyx", line 514, in zmq.core.socket.Socket.recv (zmq/core/socket.c:4811)\n', ' File "socket.pyx", line 548, in zmq.core.socket.Socket.recv (zmq/core/socket.c:4673)\n', ' File "socket.pyx", line 99, in zmq.core.socket._recv_copy (zmq/core/socket.c:1344)\n', 'ZMQError: Resource temporarily unavailable\n']
  44. ['Traceback (most recent call last):\n', ' File "./test.py", line 33, in <module>\n print receiver.recv_multipart(zmq.NOBLOCK)\n', ' File "socket.pyx", line 611, in zmq.core.socket.Socket.recv_multipart (zmq/core/socket.c:5181)\n', ' File "socket.pyx", line 514, in zmq.core.socket.Socket.recv (zmq/core/socket.c:4811)\n', ' File "socket.pyx", line 548, in zmq.core.socket.Socket.recv (zmq/core/socket.c:4673)\n', ' File "socket.pyx", line 99, in zmq.core.socket._recv_copy (zmq/core/socket.c:1344)\n', 'ZMQError: Resource temporarily unavailable\n']
  45. ['Traceback (most recent call last):\n', ' File "./test.py", line 33, in <module>\n print receiver.recv_multipart(zmq.NOBLOCK)\n', ' File "socket.pyx", line 611, in zmq.core.socket.Socket.recv_multipart (zmq/core/socket.c:5181)\n', ' File "socket.pyx", line 514, in zmq.core.socket.Socket.recv (zmq/core/socket.c:4811)\n', ' File "socket.pyx", line 548, in zmq.core.socket.Socket.recv (zmq/core/socket.c:4673)\n', ' File "socket.pyx", line 99, in zmq.core.socket._recv_copy (zmq/core/socket.c:1344)\n', 'ZMQError: Resource temporarily unavailable\n']
  46. ^CTraceback (most recent call last):
  47. File "./test.py", line 37, in <module>
  48. sleep(2)
  49. KeyboardInterrupt
  50. """
  51.