使用python asyncore从套接字读取固定字节数

1 投票
1 回答
645 浏览
提问于 2025-04-16 02:48

我使用asyncore来和远程服务器进行“长度:消息”这种协议的通信。有人能推荐一种方法来从套接字中读取确切的字节数吗?我试着用handle_read来填充内部缓冲区,每次调用我的函数时检查缓冲区的大小,但看起来太麻烦了(要检查缓冲区是否足够长以读取长度,检查缓冲区长度是否大于消息长度,然后再读取消息等等)。有没有可能有类似“socket.read(bytes)”的东西,它可以在缓冲区填满之前让程序暂停,然后返回值?

1 个回答

1

不行。睡眠会完全违背异步输入输出的目的。

不过,使用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,))

撰写回答