Mark Slee | c98d050 | 2006-09-06 02:42:25 +0000 | [diff] [blame] | 1 | import sys |
| 2 | import traceback |
| 3 | |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 4 | from thrift.Thrift import TProcessor |
| 5 | from thrift.transport import TTransport |
| 6 | |
| 7 | class TServer: |
| 8 | |
| 9 | """Base interface for a server, which must have a run method.""" |
| 10 | |
Mark Slee | d788b2e | 2006-09-07 01:26:35 +0000 | [diff] [blame] | 11 | 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 Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 18 | |
| 19 | def run(self): |
| 20 | pass |
| 21 | |
| 22 | class TSimpleServer(TServer): |
| 23 | |
| 24 | """Simple single-threaded server that just pumps around one transport.""" |
| 25 | |
Mark Slee | d788b2e | 2006-09-07 01:26:35 +0000 | [diff] [blame] | 26 | def __init__(self, processor, serverTransport, transportFactory=None): |
| 27 | TServer.__init__(self, processor, serverTransport, transportFactory) |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 28 | |
| 29 | def run(self): |
Mark Slee | d788b2e | 2006-09-07 01:26:35 +0000 | [diff] [blame] | 30 | self.serverTransport.listen() |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 31 | while True: |
Mark Slee | d788b2e | 2006-09-07 01:26:35 +0000 | [diff] [blame] | 32 | client = self.serverTransport.accept() |
| 33 | (input, output) = self.transportFactory.getIOTransports(client) |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 34 | try: |
| 35 | while True: |
Mark Slee | d788b2e | 2006-09-07 01:26:35 +0000 | [diff] [blame] | 36 | self.processor.process(input, output) |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 37 | except Exception, x: |
Mark Slee | c98d050 | 2006-09-06 02:42:25 +0000 | [diff] [blame] | 38 | print '%s, %s, %s' % (type(x), x, traceback.format_exc()) |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 39 | print 'Client died.' |
Mark Slee | d788b2e | 2006-09-07 01:26:35 +0000 | [diff] [blame] | 40 | |
| 41 | input.close() |
| 42 | output.close() |