扭曲Int16StringReceiver小端字节顺序

时间:2015-02-03 18:24:52

标签: python python-2.7 byte twisted

我尝试使用twisted提供的this class来构建我的tcp流。但它们的默认格式是大端字节顺序,但我需要用小端读取。

所以我做了:

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

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

但由于某种原因stringReceived很少被调用。客户端和服务器都在同一台机器上,我非常确定客户端确实发送了数据。

那么为什么每次收到数据时都不会调用stringReceived

我尝试覆盖dataReceived

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

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

每次客户端发送数据时都会打印出来。那么为什么没有被stringReceived召唤?也许是一个错过帧?但为什么呢?

1 个答案:

答案 0 :(得分:2)

客户端应该发送这样的消息:

len(string)string

其中len(字符串) - 应根据服务器使用的格式打包。

以下是IntNStringReceiver.sendString

中发生的情况
 self.transport.write(
     pack(self.structFormat, len(string)) + string)

要确认,Int16StringReceiver不是整数发送者/接收者。它的作用是:以上述格式通过传输发送字节消息。并且以你做的方式覆盖dataReceived是个坏主意。您可以在源代码中看到此方法非常复杂。

我的建议:确保客户端真正发送len(string)string,其中len(string)使用<H格式打包。

我测试了一个使用与服务器格式不同的客户端,服务器就疯了。

相关问题