Search code examples
pythonsocketsasyncore

Reading fixed amount of bytes from socket with python asyncore


I use asyncore to communicate with remote servers using "length:message"-type protocol. Can someone recommend me a way to read exact amount of bytes from socket? I was trying to use handle_read to fill internal buffer and call my function every time, checking for size of buffer, but it looked too ugly(Check if buffer is long enough to read length, check if buffer length is bigger than message length, read message, etc...). Is it possible to have something like "socket.read(bytes)" which would sleep until buffer is filled enough and return value?


Solution

  • No. Sleeping would defeat the entire purpose of asynchronous IO.

    However, this is remarkably simple to do with twisted.

    from twisted.protocols.basic import Int32StringReceiver
    
    class YourProtocol(Int32StringReceiver):
        def connectionMade(self):
            self.sendString('This string will automatically have its length '
                'prepended before it\'s sent over the wire!')
    
        def stringReceived(self, string):
            print ('Received %r, which came in with a prefixed length, but which '
                'has been stripped off for convenience.' % (string,))