import socket import asyncore import sys MSG_SIZE = 4096 DATA = (MSG_SIZE * ' ' + '\n').encode() 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) def writable(self): return False def handle_read(self): self.recv(64) self.close() 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) self.cnt = 0 def handle_connect(self, *args): self.send(DATA) def handle_write(self): print('handle_write') asyncore.dispatcher_with_send.handle_write(self) def handle_read(self): print('handle_read') self.recv(MSG_SIZE) def handle_close(self): print('handle_close') if not self.writable(): self.close() # abort to stop infinite calls to handle_read handle_close self.cnt += 1 if self.cnt == 20: print('Aborting: too many calls to handle_close.') sys.exit() def main(): address = ('localhost', 3220) Server(address) Writer(address) asyncore.loop(timeout=LOOP_TIMEOUT) if __name__ == "__main__": main()