使用python asyncore从套接字读取固定字节数
问题描述:
我使用asyncore使用“length:message”类型协议与远程服务器进行通信。有人可以推荐我一种从套接字读取确切字节数的方法吗?我试图使用handle_read填充内部缓冲区并每次调用我的函数,检查缓冲区的大小,但它看起来太难看了(检查缓冲区是否足够长以便读取长度,检查缓冲区长度是否大于消息长度,读取消息等)。是否有可能有类似“socket.read(字节)”的东西睡觉,直到缓冲区充足并返回值?使用python asyncore从套接字读取固定字节数
答
不会。睡觉会挫败异步IO的全部目的。
但是,这与twisted非常简单。
from twisted.protocols.basic import Int32StringReceiver
class YourProtocol(Int32StringReceiver):
def connectionMade(self):
self.sendString('This string will automatically have its length '
'prepended before it\'s sent over the wire!')
def stringReceived(self, string):
print ('Received %r, which came in with a prefixed length, but which '
'has been stripped off for convenience.' % (string,))
我希望避免扭曲,但这看起来像一个非常好的解决方案。但是,是否有办法同时处理具有稍微不同格式的消息?类似length:message:additional_data其中附加数据具有固定长度但该长度未包含在前缀长度中?例如“4:test:fixed_length_string”,只有在满足特殊条件时才会发生这种情况,但我也需要访问这个additional_data。 – Riz 2010-08-14 21:12:58
这使得它稍微复杂一些,但不是太糟糕。就个人而言,我建议使用'qbuf'第三方模块来做到这一点。我会在一秒之内发布如何使用它的例子。 – habnabit 2010-08-14 21:18:53