twisted Int16StringReceiver little endian byte order

雨燕双飞 提交于 2020-04-30 07:42:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28306076/twisted-int16stringreceiver-little-endian-byte-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!