def read(self): """ :return: """ if self.running and (self.socket is not None): try: data = self.socket.recv(self.READ_BUFFER_SIZE) if not data: self.running = False self.socket.shutdown(socket.SHUT_RDWR) raise CloseClientException("read, but empty data") except socket.error, e: if e.args[0] in (ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED): self.running = False self.socket.shutdown(socket.SHUT_RDWR) raise ClientException("socket read error:%s" % except_info()) else: raise self.read_buffer += data if len(self.read_buffer) > self.MAX_READ_BUFFER_SIZE: raise ClientException("Maxread buffer size reached")
def loop(self): """dispatch socket to handler :return: """ while True: try: events = self.poll.poll(0.01) for fd, event in events: # connect if fd == self.server_sock.fileno(): if event & Poll.ERROR: self.logger.debug("fd:%d event:ERROR" % fd) self.logger.error("server socket error") break elif event & Poll.READ: self.logger.debug("fd:%d event:READ" % fd) self._connect() elif event & Poll.READ: self.logger.debug("fd:%d event:READ" % fd) self._read(fd) elif event & Poll.WRITE: self.logger.debug("fd:%d event:WRITE" % fd) self._write(fd) elif event & Poll.ERROR: self.logger.debug("fd:%d event:ERROR" % fd) if fd in self.clients: self.clients[fd].close() del self.clients[fd] self._update(fd) except: self.logger.error(except_info()) break
def start(self, address): try: # server socket self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_sock.setblocking(0) self.server_sock.bind(address) self.server_sock.listen(self.LISTEN_COUNT) self.poll.register(self.server_sock.fileno(), Poll.READ | Poll.ERROR) self.logger.debug("info:\nserver_sock:%d" % (self.server_sock.fileno())) # loop self.loop() except: self.logger.error(except_info()) # close socket self._clean() try: self.poll.unregister(self.server_sock.fileno()) self.server_sock.close() except: # ignore pass self.server_sock = None
def _update(self, fd): client = self.clients.get(fd, None) if client is not None: try: client.process() except: self.logger.warn("one client update error: %s" % except_info()) self.poll.unregister(fd) del self.clients[fd] client.close() elif fd in self.clients: del self.clients[fd]
def _write(self, fd): """write :param fd: :return: """ client = self.clients.get(fd, None) if client is not None: try: client.write() except: self.logger.warn("one client write error: %s" % except_info()) self.poll.unregister(fd) del self.clients[fd] client.close() elif fd in self.clients: del self.clients[fd]
def _read(self, fd): """ :param fd: :return: """ client = self.clients.get(fd, None) if client is not None: try: client.read() except CloseClientException: self.poll.unregister(fd) self.clients[fd] client.close() except: self.logger.warn("one client read error: %s" % except_info()) self.poll.unregister(fd) del self.clients[fd] client.close() elif fd in self.clients: del self.clients[fd]