filesocket.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # -*- coding: utf-8 -*-
  2. """
  3. sleekxmpp.xmlstream.filesocket
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This module is a shim for correcting deficiencies in the file
  6. socket implementation of Python2.6.
  7. Part of SleekXMPP: The Sleek XMPP Library
  8. :copyright: (c) 2011 Nathanael C. Fritz
  9. :license: MIT, see LICENSE for more details
  10. """
  11. from socket import _fileobject
  12. import errno
  13. import socket
  14. class FileSocket(_fileobject):
  15. """Create a file object wrapper for a socket to work around
  16. issues present in Python 2.6 when using sockets as file objects.
  17. The parser for :class:`~xml.etree.cElementTree` requires a file, but
  18. we will be reading from the XMPP connection socket instead.
  19. """
  20. def read(self, size=4096):
  21. """Read data from the socket as if it were a file."""
  22. if self._sock is None:
  23. return None
  24. while True:
  25. try:
  26. data = self._sock.recv(size)
  27. break
  28. except socket.error as serr:
  29. if serr.errno != errno.EINTR:
  30. raise
  31. if data is not None:
  32. return data
  33. class Socket26(socket.socket):
  34. """A custom socket implementation that uses our own FileSocket class
  35. to work around issues in Python 2.6 when using sockets as files.
  36. """
  37. def makefile(self, mode='r', bufsize=-1):
  38. """makefile([mode[, bufsize]]) -> file object
  39. Return a regular file object corresponding to the socket. The mode
  40. and bufsize arguments are as for the built-in open() function."""
  41. return FileSocket(self._sock, mode, bufsize)