Search code examples
pythonpython-2.7bytetwisted

twisted Int16StringReceiver little endian byte order


I'm trying to use this class provided by twisted to frame my tcp stream. But the default format they have is in big endian byte order but I need to read in little endian.

So I did:

class Player(basic.Int16StringReceiver):
    structFormat = "<H"

    def stringReceived(self, packet):
        print ':'.join(x.encode('hex') for x in packet)

But for some reason stringReceived seldom gets called. Both client and server is on the same machine and I am very sure the client did send the data.

So why is stringReceived not being called every time data is received.

I tried overriding dataReceived:

class Player(basic.Int16StringReceiver):
    structFormat = "<H"

    def dataReceived(self, recd):
        print ':'.join(x.encode('hex') for x in recd)

And it does print out every time the client sends data. So why isn't stringReceived getting called? Maybe a miss-frame? But why?


Solution

  • Client is supposed to send message like this:

    len(string)string
    

    where len(string) - should be packed according to format used by server.

    Here is what happens in IntNStringReceiver.sendString

     self.transport.write(
         pack(self.structFormat, len(string)) + string)
    

    Just to confirm, Int16StringReceiver is not integers sender/receiver. What it does is: send bytes messages over transport in the format mentioned above. And it is bad idea to override dataReceived the way you did it. This method is pretty complicated as you can see in the source code.

    My advise: make sure client really sends len(string)string, where len(string) is packed using <H format.

    I tested a client that use different from server format, and the server just goes crazy.