blob: 53260b87e98001c6166a3941b695204474343b92 [file] [log] [blame]
Mark Sleec98d0502006-09-06 02:42:25 +00001import sys
2import traceback
3
Mark Sleec9676562006-09-05 17:34:52 +00004from thrift.Thrift import TProcessor
5from thrift.transport import TTransport
6
7class TServer:
8
Mark Slee794993d2006-09-20 01:56:10 +00009 """Base interface for a server, which must have a serve method."""
Mark Sleec9676562006-09-05 17:34:52 +000010
Mark Sleed788b2e2006-09-07 01:26:35 +000011 def __init__(self, processor, serverTransport, transportFactory=None):
12 self.processor = processor
13 self.serverTransport = serverTransport
14 if transportFactory == None:
15 self.transportFactory = TTransport.TTransportFactoryBase()
16 else:
17 self.transportFactory = transportFactory
Mark Sleec9676562006-09-05 17:34:52 +000018
Mark Slee794993d2006-09-20 01:56:10 +000019 def serve(self):
Mark Sleec9676562006-09-05 17:34:52 +000020 pass
21
22class TSimpleServer(TServer):
23
24 """Simple single-threaded server that just pumps around one transport."""
25
Mark Sleed788b2e2006-09-07 01:26:35 +000026 def __init__(self, processor, serverTransport, transportFactory=None):
27 TServer.__init__(self, processor, serverTransport, transportFactory)
Mark Sleec9676562006-09-05 17:34:52 +000028
Mark Slee794993d2006-09-20 01:56:10 +000029 def serve(self):
Mark Sleed788b2e2006-09-07 01:26:35 +000030 self.serverTransport.listen()
Mark Sleec9676562006-09-05 17:34:52 +000031 while True:
Mark Sleed788b2e2006-09-07 01:26:35 +000032 client = self.serverTransport.accept()
33 (input, output) = self.transportFactory.getIOTransports(client)
Mark Sleec9676562006-09-05 17:34:52 +000034 try:
35 while True:
Mark Sleed788b2e2006-09-07 01:26:35 +000036 self.processor.process(input, output)
Mark Slee4f0fed62006-10-02 17:50:08 +000037 except TTransport.TTransportException, tx:
38 pass
Mark Sleec9676562006-09-05 17:34:52 +000039 except Exception, x:
Mark Sleec98d0502006-09-06 02:42:25 +000040 print '%s, %s, %s' % (type(x), x, traceback.format_exc())
Mark Sleed788b2e2006-09-07 01:26:35 +000041
42 input.close()
43 output.close()
Mark Slee4f0fed62006-10-02 17:50:08 +000044
45class TThreadedServer(TServer):
46
47 """Threaded server that spawns a new thread per each connection."""
48
49 def __init__(self, processor, serverTransport, transportFactory=None):
50 TServer.__init__(self, processor, serverTransport, transportFactory)
51
52 def serve(self):
53 self.serverTransport.listen()
54 while True:
55 try:
56 client = self.serverTransport.accept()
57 t = threading.Thread(target = self.handle, args=(client,))
58 t.start()
59 except Exception, x:
60 print '%s, %s, %s,' % (type(x), x, traceback.format_exc())
61
62 def handle(self, client):
63 (input, output) = self.transportFactory.getIOTransports(client)
64 try:
65 while True:
66 self.processor.process(input, output)
67 except TTransport.TTransportException, tx:
68 pass
69 except Exception, x:
70 print '%s, %s, %s' % (type(x), x, traceback.format_exc())