我使用 asyncore 与使用“长度:消息”类型协议的远程服务器进行通信。有人可以推荐我一种从套接字读取确切字节数的方法吗?我试图使用handle_read来填充内部缓冲区并每次调用我的函数,检查缓冲区的大小,但它看起来太丑了(检查缓冲区是否足够长以读取长度,检查缓冲区长度是否大于消息长度,读取消息等...)。是否有可能有像“socket.read(bytes)”这样的东西,它会一直休眠直到缓冲区被填满并返回值?
问问题
599 次
1 回答
1
不会。睡眠会破坏异步 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,))
于 2010-08-14T20:57:59.773 回答