def read_from_fd(self): try: chunk = self.sock.receive() except socket.timeout as e: # 服务器是不会recv超时的 raise e except socket.error as e: if e.errno == errno.EINTR: # 中断,返回空字符串,但不断掉连接 return '' else: logger.error('exc occur.', exc_info=True) self.close() return None except KeyboardInterrupt as e: # 中断 raise e except: logger.error('exc occur.', exc_info=True) # 其他都直接关闭 self.close() return None if not chunk: self.close() return None # 如果二进制传输,获取的将会是bytearray,会导致box.body是bytearray格式,从而导致protobuf parse报错 # 为了同时兼容python2和python3,使用bytes强制转化 return bytes(chunk)
def shutdown_fd(self, how=2): try: self.sock.stream.handler.socket.shutdown(how) except KeyboardInterrupt as e: # 中断 raise e except: logger.error('exc occur.', exc_info=True)
def write_to_fd(self, data): try: return self.sock.send(data, binary=True) except KeyboardInterrupt as e: # 中断 raise e except: logger.error('exc occur. data: %r', data, exc_info=True) return None
def close_fd(self): try: self.sock.close() except KeyboardInterrupt as e: # 中断 raise e except: logger.error('exc occur.', exc_info=True) finally: self.sock = None
class WSStream(Stream): def read_from_fd(self): try: chunk = self.sock.receive() except socket.timeout, e: # 服务器是不会recv超时的 raise e except socket.error, e: if e.errno == errno.EINTR: # 中断,返回空字符串,但不断掉连接 return '' else: logger.error('exc occur.', exc_info=True) self.close() return None
except socket.timeout, e: # 服务器是不会recv超时的 raise e except socket.error, e: if e.errno == errno.EINTR: # 中断,返回空字符串,但不断掉连接 return '' else: logger.error('exc occur.', exc_info=True) self.close() return None except KeyboardInterrupt, e: # 中断 raise e except: logger.error('exc occur.', exc_info=True) # 其他都直接关闭 self.close() return None if not chunk: self.close() return None # 如果二进制传输,获取的将会是bytearray,会导致box.body是bytearray格式,从而导致protobuf parse报错 return str(chunk) def write_to_fd(self, data): try: return self.sock.send(data, binary=True) except KeyboardInterrupt, e:
except socket.timeout, e: # 服务器是不会recv超时的 raise e except socket.error, e: if e.errno == errno.EINTR: # 中断,返回空字符串,但不断掉连接 return '' else: logger.error('exc occur.', exc_info=True) self.close() return None except KeyboardInterrupt, e: # 中断 raise e except: logger.error('exc occur.', exc_info=True) # 其他都直接关闭 self.close() return None if not chunk: self.close() return None # 如果二进制传输,获取的将会是bytearray,会导致box.body是bytearray格式,从而导致protobuf parse报错 return str(chunk) def write_to_fd(self, data): try: return self.sock.send(data) except KeyboardInterrupt, e: