summaryrefslogtreecommitdiff
path: root/sleekxmpp/xmlstream/filesocket.py
blob: 56554c736d9b6d5b80e695a922c93d63ffbcdbbf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# -*- coding: utf-8 -*-
"""
    sleekxmpp.xmlstream.filesocket
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    This module is a shim for correcting deficiencies in the file
    socket implementation of Python2.6.

    Part of SleekXMPP: The Sleek XMPP Library

    :copyright: (c) 2011 Nathanael C. Fritz
    :license: MIT, see LICENSE for more details
"""

from socket import _fileobject
import socket


class FileSocket(_fileobject):

    """Create a file object wrapper for a socket to work around
    issues present in Python 2.6 when using sockets as file objects.

    The parser for :class:`~xml.etree.cElementTree` requires a file, but
    we will be reading from the XMPP connection socket instead.
    """

    def read(self, size=4096):
        """Read data from the socket as if it were a file."""
        if self._sock is None:
            return None
        data = self._sock.recv(size)
        if data is not None:
            return data


class Socket26(socket._socketobject):

    """A custom socket implementation that uses our own FileSocket class
    to work around issues in Python 2.6 when using sockets as files.
    """

    def makefile(self, mode='r', bufsize=-1):
        """makefile([mode[, bufsize]]) -> file object
        Return a regular file object corresponding to the socket.  The mode
        and bufsize arguments are as for the built-in open() function."""
        return FileSocket(self._sock, mode, bufsize)