Python 异步套接字接收不工作

标签 python sockets python-3.x asyncsocket

这是一个连接并发送文本消息的简单客户端:

class Client(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.connect( (host, port) )
        self.buffer = bytes("hello world", 'ascii')

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print(self.recv(8192))

    def writable(self):
        return (len(self.buffer) > 0)

    def writable(self):
        return True

    def handle_write(self):
        sent = self.send(self.buffer)
        print('Sent:', sent)
        self.buffer = self.buffer[sent:]


client = Client('localhost', 8080)
asyncore.loop()

这是必须接收消息并将其回显的服务器:

class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_read(self):
        self.buffer = self.recv(4096)
        while True:
            partial = self.recv(4096)
            print('Partial', partial)
            if not partial:
                break
            self.buffer += partial

    def readable(self):
        return True

    def handle_write(self):
        pass

    def handle_accepted(self, sock, addr):
        print('Incoming connection from %s' % repr(addr))
        self.handle_read()
        print(self.buffer)


if __name__ == "__main__":
    server = Server("localhost", 8080)
    asyncore.loop()

问题是服务器没有读取任何东西。当我打印 self.buffer 时,输出是:

b''

我做错了什么?

最佳答案

首先,您需要两个处理程序:一个用于服务器套接字(您只期望accept),另一个用于实际的通信套接字。另外,在handle_read中只能调用一次read;如果你调用它两次,第二次调用可能会阻塞,这在 asyncore 编程中是不允许的。不过别担心;如果您的读取没有获得所有内容,您将在读取处理程序返回后立即再次收到通知。

import asyncore

class Handler(asyncore.dispatcher):
    def __init__(self, sock):
        self.buffer = b''
        super().__init__(sock)

    def handle_read(self):
        self.buffer += self.recv(4096)
        print('current buffer: %r' % self.buffer)


class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accepted(self, sock, addr):
        print('Incoming connection from %s' % repr(addr))
        Handler(sock)


if __name__ == "__main__":
    server = Server("localhost", 1234)
    asyncore.loop()

关于Python 异步套接字接收不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609332/

相关文章:

java - 编写多线程套接字代理: IOException SocketClosed where it shouldn't

python - 在新的 Python 版本上安装 Python 模块

python - 如何使用 ChemDraw/Python 从 InChI 创建 .cdx 文件?

python - 使用 RedShift 作为额外的 Django 数据库

python - 如何将 Python 连接到 Db2

python - 在 Python 中标记列表的任何快速方法?

python - 为什么我的切换数组元素的代码不够快?

python - 在 Python 中获取数组作为 GET 查询参数

c - 服务器上的多个客户端

php - 在Windows 7命令行窗口中通过PHP套接字发送JSON数据