3 # Copyright (c) 2006- Facebook
4 # Distributed under the Thrift Software License
6 # See accompanying file LICENSE or visit the Thrift site at:
7 # http://developers.facebook.com/thrift/
9 from TTransport
import *
12 class TSocket(TTransportBase
):
14 """Socket implementation of TTransport base."""
16 def __init__(self
, host
='localhost', port
=9090, unix_socket
=None):
17 """Initialize a TSocket
19 @param host(str) The host to connect to.
20 @param port(int) The (TCP) port to connect to.
21 @param unix_socket(str) The filename of a unix socket to connect to.
22 (host and port will be ignored.)
28 self
._unix
_socket
= unix_socket
31 def setHandle(self
, h
):
35 return self
.handle
!= None
37 def setTimeout(self
, ms
):
41 self
._timeout
= ms
/1000.0
43 if (self
.handle
!= None):
44 self
.handle
.settimeout(self
._timeout
)
46 def _resolveAddr(self
):
47 if self
._unix
_socket
is not None:
48 return [(socket
.AF_UNIX
, socket
.SOCK_STREAM
, None, None, self
._unix
_socket
)]
50 return socket
.getaddrinfo(self
.host
, self
.port
, socket
.AF_UNSPEC
, socket
.SOCK_STREAM
, 0, socket
.AI_PASSIVE | socket
.AI_ADDRCONFIG
)
54 res0
= self
._resolveAddr
()
56 self
.handle
= socket
.socket(res
[0], res
[1])
57 self
.handle
.settimeout(self
._timeout
)
59 self
.handle
.connect(res
[4])
60 except socket
.error
, e
:
61 if res
is not res0
[-1]:
66 except socket
.error
, e
:
67 raise TTransportException(TTransportException
.NOT_OPEN
, 'Could not connect to %s:%d' % (self
.host
, self
.port
))
70 if self
.handle
!= None:
75 buff
= self
.handle
.recv(sz
)
77 raise TTransportException('TSocket read 0 bytes')
80 def write(self
, buff
):
84 plus
= self
.handle
.send(buff
)
86 raise TTransportException('TSocket sent 0 bytes')
93 class TServerSocket(TServerTransportBase
):
95 """Socket implementation of TServerTransport base."""
97 def __init__(self
, port
):
102 res0
= socket
.getaddrinfo(None, self
.port
, socket
.AF_UNSPEC
, socket
.SOCK_STREAM
, 0, socket
.AI_PASSIVE | socket
.AI_ADDRCONFIG
)
104 if res
[0] is socket
.AF_INET6
or res
is res0
[-1]:
107 self
.handle
= socket
.socket(res
[0], res
[1])
108 self
.handle
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
, 1)
109 if hasattr(self
.handle
, 'set_timeout'):
110 self
.handle
.set_timeout(None)
111 self
.handle
.bind(res
[4])
112 self
.handle
.listen(128)
115 (client
, addr
) = self
.handle
.accept()
117 result
.setHandle(client
)