socket.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """ Defines a dummy socket implementing (part of) the zmq.Socket interface. """
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import abc
  5. import warnings
  6. try:
  7. from queue import Queue # Py 3
  8. except ImportError:
  9. from Queue import Queue # Py 2
  10. import zmq
  11. from traitlets import HasTraits, Instance, Int
  12. from ipython_genutils.py3compat import with_metaclass
  13. #-----------------------------------------------------------------------------
  14. # Generic socket interface
  15. #-----------------------------------------------------------------------------
  16. class SocketABC(with_metaclass(abc.ABCMeta, object)):
  17. @abc.abstractmethod
  18. def recv_multipart(self, flags=0, copy=True, track=False):
  19. raise NotImplementedError
  20. @abc.abstractmethod
  21. def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
  22. raise NotImplementedError
  23. @classmethod
  24. def register(cls, other_cls):
  25. if other_cls is not DummySocket:
  26. warnings.warn("SocketABC is deprecated since ipykernel version 4.5.0.",
  27. DeprecationWarning, stacklevel=2)
  28. abc.ABCMeta.register(cls, other_cls)
  29. #-----------------------------------------------------------------------------
  30. # Dummy socket class
  31. #-----------------------------------------------------------------------------
  32. class DummySocket(HasTraits):
  33. """ A dummy socket implementing (part of) the zmq.Socket interface. """
  34. queue = Instance(Queue, ())
  35. message_sent = Int(0) # Should be an Event
  36. context = Instance(zmq.Context)
  37. def _context_default(self):
  38. return zmq.Context.instance()
  39. #-------------------------------------------------------------------------
  40. # Socket interface
  41. #-------------------------------------------------------------------------
  42. def recv_multipart(self, flags=0, copy=True, track=False):
  43. return self.queue.get_nowait()
  44. def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
  45. msg_parts = list(map(zmq.Message, msg_parts))
  46. self.queue.put_nowait(msg_parts)
  47. self.message_sent += 1
  48. SocketABC.register(DummySocket)