def __init__(self, host='localhost', port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC): """Initialize a TSocket @param host(str) The host to connect to. @param port(int) The (TCP) port to connect to. @param unix_socket(str) The filename of a unix socket to connect to. (host and port will be ignored.) @param socket_family(int) The socket family to use with this socket. """ self.host = host self.port = port self._unix_socket = unix_socket self._socket_family = socket_family self._timeout = None self.socket = None self.socket_buf = SocketBuffer() self.handle = None
class TRBuffSocket(TSocketBase): __slots__ = ("host", "port", "_unix_socket", "_socket_family", "_timeout", "socket", "socket_buf", "handle") """ 1. 支持 inet, unix domain socket通信的socket 2. 带有read buffer的socket, 算法来自redis-py """ def __init__(self, host='localhost', port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC): """Initialize a TSocket @param host(str) The host to connect to. @param port(int) The (TCP) port to connect to. @param unix_socket(str) The filename of a unix socket to connect to. (host and port will be ignored.) @param socket_family(int) The socket family to use with this socket. """ self.host = host self.port = port self._unix_socket = unix_socket self._socket_family = socket_family self._timeout = None self.socket = None self.socket_buf = SocketBuffer() self.handle = None def setHandle(self, h): self.setSocket(h) def setSocket(self, s): """ 更新Socket, 以及对应的SocketBuffer """ self.socket = s self.socket_buf.update_socket(self.socket) def isOpen(self): return self.socket is not None def close(self): if self.socket: self.socket.close() self.socket = None self.socket_buf.update_socket(self.socket) def setTimeout(self, ms): if ms is None: self._timeout = None else: self._timeout = ms / 1000.0 if self.socket is not None: self.socket.settimeout(self._timeout) def open(self): try: res0 = self._resolveAddr() for res in res0: self.socket = socket.socket(res[0], res[1]) self.socket.settimeout(self._timeout) self.socket_buf.update_socket(self.socket) # 拷贝自redis-py if res[0] == socket.AF_INET: self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) try: self.socket.connect(res[4]) except socket.error, e: if res is not res0[-1]: continue else: raise e break except socket.error, e: # 遇到这种socket的Error, 似乎没有必要Retry, 直接报错 if self._unix_socket: message = 'Could not connect to socket %s' % self._unix_socket else: message = 'Could not connect to %s:%d' % (self.host, self.port) raise TTransportException(type=TTransportException.NOT_OPEN, message=message)