python - 扭曲的 Int16StringReceiver 小端字节顺序

标签 python python-2.7 byte twisted

我正在尝试使用 this class由twisted提供来构建我的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 没有被调用呢?也许是错帧?但为什么呢?

最佳答案

客户端应该发送如下消息:

len(string)string

其中 len(string) - 应根据服务器使用的格式进行打包。

这是 IntNStringReceiver.sendString 中发生的情况

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

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

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

我测试了一个使用与服务器格式不同的客户端,并且服务器变得疯狂。

关于python - 扭曲的 Int16StringReceiver 小端字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28306076/

相关文章:

java - int 的可变长度编码为 2 个字节

python - 我可以批量递增值以减少数据库写入吗?

python - 正则表达式/正则表达式 Python 2.7

python-2.7 - 执行python scikit-learn grid-search方法时出现无效参数错误

java - 从套接字 inputStream read() 返回的 Int 中获取字节

java - 由字节/短整型组成的 Java 数组比整数组成的内存效率更高吗?

python - 根据 PEP8,我应该总是在 79 个字符限制之前换行吗?

python - 比较两个数据帧列是否匹配字符串或子字符串,然后在 pandas 中计数

class - 仅在第一次调用变量时才起作用的 Pythonic 方式

python - 类型错误 Iter - Python3