扭曲的 Int16StringReceiver 小端字节序 [英] twisted Int16StringReceiver little endian byte order

查看:42
本文介绍了扭曲的 Int16StringReceiver 小端字节序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 这个类 由twisted 提供以构建我的tcp 流.但是它们的默认格式是大端字节序,但我需要以小端字节序读取.

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.

所以我做到了:

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

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

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

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.

那么为什么每次接收数据时都没有调用stringReceived.

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

我尝试覆盖dataReceived:

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

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

而且每次客户端发送数据时它都会打印出来.那么为什么没有调用 stringReceived 呢?也许是错帧?但为什么?

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

推荐答案

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

Client is supposed to send message like this:

len(string)string

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

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

这是 IntNStringReceiver.sendString

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

确认一下,Int16StringReceiver 不是整数发送方/接收方.它的作用是:以上述格式通过传输发送字节消息.并且按照您的方式覆盖 dataReceived 是个坏主意.如您在源代码中所见,此方法非常复杂.

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.

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

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.

这篇关于扭曲的 Int16StringReceiver 小端字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆