import socket import asyncore MSG_SIZE = 4096 DATA = b'\0' * MSG_SIZE LOOP_TIMEOUT = .020 class Server(asyncore.dispatcher): def __init__(self, address): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(address) self.listen(1) def handle_accept(self): sock, addr = self.accept() Reader(sock) self.close() class Reader(asyncore.dispatcher): def __init__(self, sock): asyncore.dispatcher.__init__(self, sock) self.shutdown = False def writable(self): return False def handle_read(self): self.recv(64) if not self.shutdown: self.shutdown = True self.socket.shutdown(socket.SHUT_WR) class Writer(asyncore.dispatcher_with_send): def __init__(self, address): asyncore.dispatcher_with_send.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(address) def handle_connect(self, *args): self.send(DATA) def handle_write(self): asyncore.dispatcher_with_send.handle_write(self) if len(self.out_buffer) == 0: print('Done.') self.close() def handle_close(self): print('calling handle_close') asyncore.dispatcher_with_send.handle_close(self) def main(): address = ('localhost', 3220) Server(address) Writer(address) asyncore.loop(timeout=LOOP_TIMEOUT) if __name__ == "__main__": main()