开发者

adding a doRead() method to an existing socket object

开发者 https://www.devze.com 2023-01-23 05:56 出处:网络
is there any way to add a doRead() method to an existing socket object? the socket needs a doRead method to be able to be passed to twisted\'s reactor via the addWriter method.

is there any way to add a doRead() method to an existing socket object?

the socket needs a doRead method to be able to be passed to twisted's reactor via the addWriter method.

i've tried using the new module's instance method but it doesn't seem to work...

>>> c
<socket._socketobject object at 0x7fcb03cc8b40>
>>> c.doRead = new.instancemethod(doRead, c, socket._socketobject)
Traceback (most recent call last):
  File "<stdin>", line 1开发者_如何学C, in <module>
AttributeError: '_socketobject' object has no attribute 'doRead'


It's not new.instancemethod that's failing here. It's the fact that you have a socket._socketobject, an instance of an extension type, which doesn't have a __dict__ so cannot be given arbitrary new attributes.

The typical way in which you make one kind of object look like another kind of object is to use wrapping. Create a new class that has all the methods you want and gets a reference to your socket. For example:

class Connection:
    def __init__(self, socket, protocol):
        self.socket = socket
        self.protocol = protocol

    def doRead(self):
        try:
            data = self.socket.recv(self.bufferSize)
        except socket.error, se:
            if se.args[0] == EWOULDBLOCK:
                return
            else:
                return main.CONNECTION_LOST
        if not data:
            return main.CONNECTION_DONE
        return self.protocol.dataReceived(data)

This is copied straight from Twisted, of course - it is the solution to exactly the problem you are trying to solve. :)

Re-implementing the guts of Twisted might be a useful exercise to make sure you understand how all the pieces work and fit together, but when you get stuck, the Twisted source itself makes a pretty good reference to help you on your way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号