class Server(object): def __init__(self, addr, coder=None): self.loop = Loop() self.acceptor = Acceptor(addr, self.loop) self.coder = coder self.clients = {} self.acceptor.set_error_callback(self.fatal_error) self.acceptor.set_connect_callback(self.process_new) def start(self): self.acceptor.listen() self.loop.loop() def fatal_error(self, msg): print msg self.quit() def quit(self): for fd in self.clients.keys(): ch = self.clients.pop(fd) ch.close() self.loop.quit() def process_new(self, sock): ch = Channel(Socket(sock), self.loop, self.coder) ch.set_read_callback(self.on_msg_in) ch.set_write_callback(self.on_msg_sent) ch.set_error_callback(self.on_error) ch.set_peer_closed(self.peer_closed) self.clients[ch.fd] = ch self.on_connect(ch) def on_connect(self, ch=None): print 'client {} connect.'.format(ch.peer_addr) pass def on_msg_in(self, msg, ch=None): pass def on_msg_sent(self, ch=None): pass def on_error(self, ch=None): print 'error' self.clients.pop(ch.fd) def peer_closed(self, ch=None): print 'client {} disconnect.'.format(ch.peer_addr) self.clients.pop(ch.fd)
class Connector(object): def __init__(self, addr, retry_times=3): self.sock = Socket() self.fd = self.sock.fd self.addr = addr self.loop = Loop(2) self.loop.set_timeout(2, self.on_timeout) self.times = retry_times self.retry_time = 0 self.stat = 0 def on_timeout(self): if self.retry_time > self.times: self.close() return self.retry_time += 1 self.loop.set_timeout(self.retry_time, self.on_timeout) if self.sock.connect(self.addr): self.on_connect() def run_onece(self, fd, evt): if evt < 8: self.on_connect() # else: # print 'connector ', evt def on_connect(self): self.close() self.stat = 1 self.sock.stat = 1 def close(self): self.loop.unregister(self.fd) self.loop.quit() def poll(self): self.loop.register(self.fd, EPOLLET | EPOLLOUT, self.run_onece) self.loop.loop() def connect(self): self.sock.connect(self.addr) self.poll() if self.stat: print 'connected' return self.sock return None
class Client(object): def __init__(self, addr, coder=None): self.sock = None self.addr = addr self.coder = coder self.loop = Loop() self.ch = None def start(self): self.connect() self.loop.loop() def connect(self, retry=3): self.sock = Connector(self.addr).connect() if not self.sock: print 'connect timeout.' exit() self.ch = Channel(self.sock, self.loop, self.coder) self.ch.set_read_callback(self.on_msg_in) self.ch.set_write_callback(self.on_msg_sent) self.ch.set_error_callback(self.on_error) self.ch.set_peer_closed(self.peer_closed) def on_msg_in(self, msg, ch=None): pass def on_msg_sent(self, ch=None): pass def on_error(self, ch=None): pass def peer_closed(self, ch=None): print 'server offline.' self.loop.quit() def send(self, msg): self.ch.send(msg)