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

发布于 2024-09-14 12:33:55 字数 218 浏览 4 评论 0原文

我使用 asyncore 使用“length:message”类型的协议与远程服务器进行通信。有人可以推荐我一种从套接字读取确切字节数的方法吗?我试图使用handle_read来填充内部缓冲区并每次调用我的函数,检查缓冲区的大小,但它看起来太丑陋(检查缓冲区是否足够长以读取长度,检查缓冲区长度是否大于消息长度,读取消息等)。是否有可能有类似“socket.read(bytes)”的东西,它会休眠直到缓冲区填满并返回值?

I use asyncore to communicate with remote servers using "length:message"-type protocol. Can someone recommend me a way to read exact amount of bytes from socket? I was trying to use handle_read to fill internal buffer and call my function every time, checking for size of buffer, but it looked too ugly(Check if buffer is long enough to read length, check if buffer length is bigger than message length, read message, etc...). Is it possible to have something like "socket.read(bytes)" which would sleep until buffer is filled enough and return value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仙女山的月亮 2024-09-21 12:33:55

不。睡眠会破坏异步 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,))

No. Sleeping would defeat the entire purpose of asynchronous IO.

However, this is remarkably simple to do with 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,))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文