扭曲的 Int16StringReceiver 小端字节序
twisted Int16StringReceiver little endian byte order
我正在尝试使用由 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
没有被调用呢?也许是失帧?但是为什么?
客户端应该像这样发送消息:
len(string)string
其中 len(string) - 应根据服务器使用的格式进行打包。
这是 IntNStringReceiver.sendString
中发生的事情
self.transport.write(
pack(self.structFormat, len(string)) + string)
确认一下,Int16StringReceiver
不是整数 sender/receiver。它的作用是:以上述格式通过传输发送字节消息。按照您的方式覆盖 dataReceived
是个坏主意。正如您在源代码中看到的那样,此方法非常复杂。
我的建议:确保客户端真的发送 len(string)string
,其中 len(string)
使用 <H
格式打包。
我测试了一个使用不同于服务器格式的客户端,然后服务器就疯了。
我正在尝试使用由 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
没有被调用呢?也许是失帧?但是为什么?
客户端应该像这样发送消息:
len(string)string
其中 len(string) - 应根据服务器使用的格式进行打包。
这是 IntNStringReceiver.sendString
self.transport.write(
pack(self.structFormat, len(string)) + string)
确认一下,Int16StringReceiver
不是整数 sender/receiver。它的作用是:以上述格式通过传输发送字节消息。按照您的方式覆盖 dataReceived
是个坏主意。正如您在源代码中看到的那样,此方法非常复杂。
我的建议:确保客户端真的发送 len(string)string
,其中 len(string)
使用 <H
格式打包。
我测试了一个使用不同于服务器格式的客户端,然后服务器就疯了。