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):
21 def setHandle(self
, h
):
25 return self
.handle
!= None
27 def setTimeout(self
, ms
):
28 if (self
.handle
!= None):
29 self
.handle
.settimeout(ms
/1000.00)
31 raise TTransportException(TTransportException
.NOT_OPEN
, 'No handle yet in TSocket')
35 res0
= socket
.getaddrinfo(self
.host
, self
.port
, socket
.AF_UNSPEC
, socket
.SOCK_STREAM
, 0, socket
.AI_PASSIVE | socket
.AI_ADDRCONFIG
)
37 self
.handle
= socket
.socket(res
[0], res
[1])
39 self
.handle
.connect(res
[4])
40 except socket
.error
, e
:
41 if res
is not res0
[-1]:
46 except socket
.error
, e
:
47 raise TTransportException(TTransportException
.NOT_OPEN
, 'Could not connect to %s:%d' % (self
.host
, self
.port
))
50 if self
.handle
!= None:
55 buff
= self
.handle
.recv(sz
)
57 raise TTransportException('TSocket read 0 bytes')
60 def write(self
, buff
):
64 plus
= self
.handle
.send(buff
)
66 raise TTransportException('TSocket sent 0 bytes')
73 class TServerSocket(TServerTransportBase
):
75 """Socket implementation of TServerTransport base."""
77 def __init__(self
, port
):
82 res0
= socket
.getaddrinfo(None, self
.port
, socket
.AF_UNSPEC
, socket
.SOCK_STREAM
, 0, socket
.AI_PASSIVE | socket
.AI_ADDRCONFIG
)
84 if res
[0] is socket
.AF_INET6
or res
is res0
[-1]:
87 self
.handle
= socket
.socket(res
[0], res
[1])
88 self
.handle
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
, 1)
89 if hasattr(self
.handle
, 'set_timeout'):
90 self
.handle
.set_timeout(None)
91 self
.handle
.bind(res
[4])
92 self
.handle
.listen(128)
95 (client
, addr
) = self
.handle
.accept()
97 result
.setHandle(client
)