import sys sys.path.append('gen-py') from thrift.transport import TSocket from thrift.server import TServer from calculadora import Calculadora class CalculadoraHandler: def suma(self, numero1, numero2): return numero1 + numero2 def resta(self, numero1, numero2): return numero1 - numero2 def multiplicacion(self, numero1, numero2): return numero1 * numero2 def division(self, numero1, numero2): return numero1 / numero2 if (numero2 != 0) else 0 if __name__ == "__main__": socket = TSocket.TServerSocket(port=9000) procesador = Calculadora.Processor(CalculadoraHandler()) server = TServer.TSimpleServer(procesador, socket) print("Iniciando servidor...") server.serve()
def main(cfg): if cfg.unix: if cfg.addr == "": sys.exit("invalid listener unix domain socket: {}".format( cfg.addr)) else: try: (host, port) = cfg.addr.rsplit(":", 1) port = int(port) except ValueError: sys.exit("invalid listener address: {}".format(cfg.addr)) if cfg.response == "success": handler = SuccessHandler() elif cfg.response == "idl-exception": handler = IDLExceptionHandler() elif cfg.response == "exception": # squelch traceback for the exception we throw logging.getLogger().setLevel(logging.CRITICAL) handler = ExceptionHandler() else: sys.exit("unknown server response mode {0}".format(cfg.response)) processor = Example.Processor(handler) if cfg.service is not None: # wrap processor with multiplexor multi = TMultiplexedProcessor.TMultiplexedProcessor() multi.registerProcessor(cfg.service, processor) processor = multi if cfg.protocol == "finagle": # wrap processor with finagle request/response header handler processor = TFinagleServerProcessor.TFinagleServerProcessor(processor) if cfg.unix: transport = TSocket.TServerSocket(unix_socket=cfg.addr) else: transport = TSocket.TServerSocket(host=host, port=port) if cfg.transport == "framed": transport_factory = TTransport.TFramedTransportFactory() elif cfg.transport == "unframed": transport_factory = TTransport.TBufferedTransportFactory() elif cfg.transport == "header": transport_factory = THeaderTransport.THeaderTransportFactory() else: sys.exit("unknown transport {0}".format(cfg.transport)) if cfg.protocol == "binary": protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() elif cfg.protocol == "compact": protocol_factory = TCompactProtocol.TCompactProtocolFactory() elif cfg.protocol == "json": protocol_factory = TJSONProtocol.TJSONProtocolFactory() elif cfg.protocol == "finagle": protocol_factory = TFinagleServerProtocol.TFinagleServerProtocolFactory( ) else: sys.exit("unknown protocol {0}".format(cfg.protocol)) print("Thrift Server listening on {0} for {1} {2} requests".format( cfg.addr, cfg.transport, cfg.protocol)) if cfg.service is not None: print("Thrift Server service name {0}".format(cfg.service)) if cfg.response == "idl-exception": print("Thrift Server will throw IDL exceptions when defined") elif cfg.response == "exception": print("Thrift Server will throw Thrift exceptions for all messages") server = TServer.TSimpleServer(processor, transport, transport_factory, protocol_factory) try: server.serve() except KeyboardInterrupt: print
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'David Zhang' from thrift import Thrift from thrift.transport import TSocket, TTransport from thrift.protocol import TCompactProtocol from thrift.server import TServer from pythrift import PersonService, ttypes class PersonServiceHandler(PersonService.Iface): def getPersonByUsername(self, username): return ttypes.Person(username, 20, False) def savePerson(self, person): print(person) if __name__ == '__main__': try: TServer.TSimpleServer( PersonService.Processor(PersonServiceHandler()), # 注意py3的socket tcp通信默认采用tcpv6 TSocket.TServerSocket(host='127.0.0.1', port=8899), TTransport.TFramedTransportFactory(), TCompactProtocol.TCompactProtocolFactory()).serve() except Thrift.TException as ex: print(ex)
from spiderserver.api import SpiderService class SpiderHandler: def runSpider(self): run_spider() if __name__ == '__main__': # 4. create a Thrift Server's handle function handler = SpiderHandler() # from message.api import MessageService processor = SpiderService.Processor(handler) # 1. create a Thrift Server's ServerSocket server_socket = TSocket.TServerSocket(host='127.0.0.1', port=9090) # server_socket = TSocket.TServerSocket(None, port=9090) # 2. create a Thrift Server's Transport --- 帧传输方式 transport_factory = TTransport.TFramedTransportFactory() # 3. create a Thrift Server's Protocal --- 二进制传输协议 protocal_factory = TBinaryProtocol.TBinaryProtocolFactory() # 5. create a Thrift Server 谁处理(who)、监听那个端口(where)、传输方式(how)、传输协议(protocal) thrift_server = TServer.TSimpleServer(processor, server_socket, transport_factory, protocal_factory) # 6. run Thrift Server, waiting for Client's access print("Spider Thrift Server run...") thrift_server.serve() print("Spider Thrift Server exit!")
def sendEmailMessage(self, email, message): print(email + message) messageObj = MIMEText(message, 'plain', 'utf-8') messageObj['From'] = sender messageObj['To'] = email messageObj['Subject'] = Header("邮箱验证", 'uf-8') try: smtpObj = smtplib.SMTP('smtp.163.com') smtpObj.login(sender, authorCode) smtpObj.sendmail(sender, [email], messageObj.as_string()) print("发送成功") return True except smtplib.SMTPException: print("发送失败") return False if __name__ == '__main__': #监听服务器端口(本机) serverSocket = TSocket.TServerSocket(host='127.0.0.1', port='9090') transportFactory = TTransport.TFramedTransportFactory() protocolFactory = TBinaryProtocol.TBinaryProtocolFactory() handler = MessageServiceHandler() processor = MessageService.Processor(handler) thriftServer = TServer.TSimpleServer(handler, serverSocket, transportFactory, protocolFactory) print("启动中") thriftServer.serve() print("退出")
def start_extension(name="<unknown>", version="0.0.0", sdk_version="1.8.0", min_sdk_version="1.8.0"): """Start your extension by communicating with osquery core and starting a thrift server. Keyword arguments: name -- the name of your extension version -- the version of your extension sdk_version -- the version of the osquery SDK used to build this extension min_sdk_version -- the minimum version of the osquery SDK that you can use """ args = parse_cli_params() # Disable logging for the thrift module (can be loud). logging.getLogger('thrift').addHandler(logging.NullHandler()) client = ExtensionClient(path=args.socket) if not client.open(args.timeout): return ext_manager = ExtensionManager() # try connecting to the desired osquery core extension manager socket try: status = client.extension_manager_client().registerExtension( info=InternalExtensionInfo( name=name, version=version, sdk_version=sdk_version, min_sdk_version=min_sdk_version, ), registry=ext_manager.registry(), ) except socket.error: message = "Could not connect to %s" % args.socket raise ExtensionException( code=1, message=message, ) if status.code is not 0: raise ExtensionException( code=1, message=status.message, ) # Start a watchdog thread to monitor the osquery process. rt = threading.Thread(target=start_watcher, args=(client, args.interval)) rt.daemon = True rt.start() # start a thrift server listening at the path dictated by the uuid returned # by the osquery core extension manager ext_manager.uuid = status.uuid processor = Processor(ext_manager) transport = transport = TSocket.TServerSocket(unix_socket=args.socket + "." + str(status.uuid)) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) server.serve()
class HelloWorldHandler(): def __init__(self): pass def ping(self): return 'pong!' def say(self, message): ret = "server received: " + message print(ret) return ret if __name__ == '__main__': handler = HelloWorldHandler() #build your own handler processor = HelloWorld.Processor( handler) ##get a processor from a handler that you built transport = TSocket.TServerSocket('localhost', 9090) #get a server transport tfactory = TTransport.TBufferedTransportFactory( ) ##get a transport factory pfactory = TBinaryProtocol.TBinaryProtocolFactory( ) ##get a protocol factory server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) #get a server from the settings print("begin the server on localhost,9090") server.serve() print("Suspend the service on localhost,9090")
def restar(self, numero1, numero2): resta = numero1 - numero2 print("La resta fue: %d" % resta) return resta def multiplicar(self, numero1, numero2): multiplicacion = numero1 * numero2 print("La multiplicacion fue: %d" % multiplicacion) return multiplicacion def dividir(self, numero1, numero2): if numero2 == 0: print("La divicion con 0 no se puede") return -1 divicion = numero1 / numero2 print("La divicion fue: %f" % divicion) return divicion puerto = 9090 handler = OperacionesHandler() procesador = Calculadora.Processor(handler) transporte_serv = TSocket.TServerSocket(port=puerto) transporte_fact = TTransport.TBufferedTransportFactory() protocolo_fact = TBinaryProtocol.TBinaryProtocolFactory() servidor = TServer.TSimpleServer(procesador, transporte_serv, transporte_fact, protocolo_fact) print("Puerto: %s iniciado :D" % puerto) servidor.serve()
# -*- coding: utf-8 -*- import sys sys.path.append("../thrift") from thrift.transport import TSocket from thrift.server import TServer from uic.UserService import UserService class UserServiceHandler: def getName(self): print("[Server] Handling client request") return "你好 thrift, from the python server" handler = UserServiceHandler() processor = UserService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) server = TServer.TSimpleServer(processor, listening_socket) print("[Server] Started") server.serve()
site_rank = {1 : ("Facebook", 750000000), 2 : ("Twitter", 250000000), 3 : ("LinkedIn", 110000000) } class SocialLookupHandler(SocialLookup.Iface): def GetSiteByRank(self, rank): tup = site_rank[rank] return "" if (None==tup) else tup[0] def GetSiteRankByName(self, name, allowPartialMatch): for rank, value in site_rank.items(): if allowPartialMatch: if value[0][:len(name)] == name: return rank else: if value[0] == name: return rank return 0 def GetSitesByUsers(self, minUserCount, maxUserCount): return [v[0] for k, v in site_rank.items() if v[1] >= minUserCount and v[1] <= maxUserCount] if __name__ == "__main__": svr_trans = TSocket.TServerSocket(port=8585) processor = SocialLookup.Processor(SocialLookupHandler()) server = TServer.TSimpleServer(processor, svr_trans) server.serve()
# Local variables server_port_num = int(sys.argv[1]) # Create server side Apache Thrift configurations fileStoreHandler = ChordServerFileStoreHandler( server_port_num) # Object to handle File Store RPC calls server_processor = FileStore.Processor( fileStoreHandler ) # Mapping of FileStore Processor and File Store Handler server_socket_transport = TSocket.TServerSocket( port=server_port_num ) # Server side socket enabled with provided port number server_tfactory = TTransport.TBufferedTransportFactory( ) # Enable buffering at server side socket server_pfactory = TBinaryProtocol.TBinaryProtocolFactory( ) # Server protocol to send contents as Binary (marshalling and unmarshalling) # Creation of simple thrift server object enabled with above configurations chord_server = TServer.TSimpleServer(server_processor, server_socket_transport, server_tfactory, server_pfactory) print("Server is running ...") print( "\n------------------------------------------------------------------------------------------\n" ) chord_server.serve( ) # Start node server to serve requests in Chord structure print("Server has served all the requests successfully." + NEW_LINE_CHAR)
def createSimpleServer(self): self.server = TServer.TSimpleServer(self.processor, self.transport, self.tfactory, self.pfactory)
# -*- coding:utf-8 -*- from thrift import Thrift from py.thrift import PersonService from thrift.transport import TTransport from thrift.transport import TSocket from thrift.protocol import TCompactProtocol from thrift.server import TServer from PersonServiceImpl import PsersonServiceImpl try: personHandler = PsersonServiceImpl() processor = PersonService.Processor(personHandler) ss = TSocket.TServerSocket(port=8800, host="localhost") transFactory = TTransport.TFramedTransportFactory() protocolFactory = TCompactProtocol.TCompactProtocolFactory() server = TServer.TSimpleServer(processor, ss, transFactory, protocolFactory) server.serve() except Thrift.TException as e: pass
#Thrift modules from idls.qp_idl.query_process import QueryProcessService from idls.qp_idl.query_process.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TCompactProtocol from thrift.server import TServer # my custom utility from util.util import * from qp_handler import QueryProcessServiceHandler qphandler = QueryProcessServiceHandler(qp_conf, qplogger) qpprocessor = QueryProcessService.Processor(qphandler) qp_ip = qp_conf["services"]["qp"]["ip"] qp_port = qp_conf["services"]["qp"]["port"] qptransport = TSocket.TServerSocket(qp_ip, qp_port) qptfactory = TTransport.TBufferedTransportFactory() qppfactory = TCompactProtocol.TCompactProtocolFactory() qp_server = TServer.TSimpleServer(qpprocessor, qptransport, qptfactory, qppfactory) qplogger.info("Starting Query Process in ip \"{}\" and port {}".format( qp_ip, qp_port)) qp_server.serve() qplogger.info("Done")
from KnowledgePolicyListener import KnowledgePolicyListener from service import KnowledgeGraphPyService from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer _HOST = "0.0.0.0" _PORT = 9000 if __name__ == "__main__": handler = KnowledgePolicyListener() processor = KnowledgeGraphPyService.Processor(handler) transport = TSocket.TServerSocket(_HOST, _PORT) tFactory = TTransport.TBufferedTransportFactory() pFactory = TBinaryProtocol.TBinaryProtocolFactory() rpcServer = TServer.TSimpleServer(processor, transport, tFactory, pFactory) rpcServer.serve()
site_rank = {1 : ("Facebook", 750000000), 2 : ("Twitter", 250000000), 3 : ("LinkedIn", 110000000) } class SocialLookupHandler(SocialLookup.Iface): def GetSiteByRank(self, rank): tup = site_rank[rank] return "" if (None==tup) else tup[0] def GetSiteRankByName(self, name, allowPartialMatch): for rank, value in site_rank.items(): if allowPartialMatch: if value[0][:len(name)] == name: return rank else: if value[0] == name: return rank return 0 def GetSitesByUsers(self, minUserCount, maxUserCount): return [v[0] for k, v in site_rank.items() if v[1] >= minUserCount and v[1] <= maxUserCount] if __name__ == "__main__": trans_svr = TSocket.TServerSocket(port=9090) proc = SocialLookup.Processor(SocialLookupHandler()) server = TServer.TSimpleServer(proc, trans_svr) server.serve()
type = types[0] # 评分 字符串 scores = soup.select_one( '#interest_sectl > div.rating_wrap.clearbox > div.rating_self.clearfix > strong' ) score = scores.get_text() self.savetodb(movie_name, country, language, type, score) print(movie_name + ":insert ok") def SpiderAllUrls(self, base_url): urls = [base_url.format(str(number * 25)) for number in [0, 1, 3, 4]] # each url for url in urls: self.GetInfo(url) time.sleep(5) print("all_ok") if __name__ == '__main__': serverSocket = TSocket.TServerSocket(host='127.0.0.1', port=9090) transportFactory = TTransport.TFramedTransportFactory() protocolFactory = TBinaryProtocol.TBinaryProtocolFactory() handler = SpiderServiceHandler() processor = SpiderService.Processor(handler) thriftServer = TServer.TSimpleServer(processor, serverSocket, transportFactory, protocolFactory) print("启动中") thriftServer.serve() print("退出")
def sendIpAddress(self, ip): # send ip to DSS logger.info("[THRIFT SERVER] Receiving IP from MMT. IP:{}".format(ip)) splitted = ip.rstrip().split(':') if len(splitted) == 1: # ip do not has port url = splitted[0] port = '' else: # ip do has port url = splitted[0] port = splitted[1] updateips.in_ipsgv({"url": url, "port": port}) if __name__ == "__main__": # run thrift server handler = DssServiceHandler() proc = DssService.Processor(handler) trans_svr = TSocket.TServerSocket(port=globals.MMT_SERVER_PORT) #trans_fac = TTransport.TBufferedTransportFactory() trans_fac = TTransport.TFramedTransportFactory() proto_fac = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(proc, trans_svr, trans_fac, proto_fac) logger.info("[THRIFT SERVER] Started in port {}".format( globals.MMT_SERVER_PORT)) print("[THRIFT SERVER] Started in url {}, port {}".format( globals.MMT_SERVER_URL, globals.MMT_SERVER_PORT)) server.serve()
def get_server(service, handler, port): processor = service.Processor(handler) transport = TSocket.TServerSocket(port=port) transport_factory = TTransport.TBufferedTransportFactory() protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() return TServer.TSimpleServer(processor, transport, transport_factory, protocol_factory)
def create_server(): handler = LightPiThriftHandler() return TServer.TSimpleServer(GenericPiThriftService.Processor(handler), TSocket.TServerSocket(port=port), TTransport.TBufferedTransportFactory(), TBinaryProtocol.TBinaryProtocolFactory())
# coding=utf-8 from py.thrift.generated import PersonService from PersonServiceImpl import PersonServiceImpl from thrift import Thrift from thrift.server import TNonblockingServer from thrift.server import TServer from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TCompactProtocol try: personServerHandler = PersonServiceImpl() processer = PersonService.Processor(personServerHandler) socket = TSocket.TServerSocket(host='127.0.0.1', port=8899) transportFactory = TTransport.TFramedTransportFactory() protocalFactory = TCompactProtocol.TCompactProtocolFactory() server = TServer.TSimpleServer(processer, socket, transportFactory, protocalFactory) server.serve() except Thrift.TException as tx: print('----')
is_ipv6 = '-6' if ':' in server_ip else '' command = "iperf3 {} -J -t 1 -c {}".format(is_ipv6, server_ip) client_loop_cnt = 0 while client_loop_cnt < client_retries: try: response = self.check_output(command) break except Exception: client_loop_cnt += 1 error_msg = '{} retries to reach iperf3 server {}' \ .format(client_loop_cnt, server_ip) response = json.dumps({'error': error_msg}) time.sleep(1) return response if __name__ == '__main__': handler = TestServer() transport = TSocket.TServerSocket(DEFAULT_PORT) tfactory = TTransport.TBufferedTransportFactory() pfactory = THeaderProtocol.THeaderProtocolFactory() server = TServer.TSimpleServer(handler, transport, tfactory, pfactory) # You could do one of these for a multithreaded server # server = TServer.TThreadedServer(handler, transport, tfactory, pfactory) print('Starting the server...') server.serve() print('done.')
def create_server(): handler = ShortTermMemoryThriftServer() return TServer.TSimpleServer(ShortMemoryService.Processor(handler), TSocket.TServerSocket(port=port), TTransport.TBufferedTransportFactory(), TBinaryProtocol.TBinaryProtocolFactory())
def wrappee(*args, **kwargs): logging.debug('in decorator before wrapee with flag ' + dec_name) if "use_rpc" not in kwargs: use_rpc = False logging.warning("Defaulting to not use RPC for: " + dec_name) else: use_rpc = kwargs["use_rpc"] if "server" not in kwargs: use_server = False logging.warning("Defaulting to not start as server for: " + dec_name) else: use_server = kwargs["server"] if use_rpc and use_server: from thrift.protocol import TBinaryProtocol from thrift.transport import TSocket from thrift.transport import TTransport from thrift.server import TServer handler = original_clazz(*args, **kwargs) processor = decorator_self._thrift_class.Processor(handler) transport = TSocket.TServerSocket(port=decorator_self._port) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() self.__inst = handler if decorator_self._server_type == "THREADED": server = TServer.TThreadedServer(processor, transport, tfactory, pfactory) elif decorator_self._server_type == "SIMPLE": server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) elif decorator_self._server_type == "FORK": server = TServer.TForkingServer(processor, transport, tfactory, pfactory) elif decorator_self._server_type == "POOL": server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) server.setNumThreads(decorator_self._pool_size) else: server = None logging.debug(decorator_self._server_type + " server serving: " + dec_name) server.serve() logging.debug('Done: ' + dec_name) elif use_rpc and not use_server: from thrift.protocol import TBinaryProtocol from thrift.transport import TSocket from thrift.transport import TTransport from thrift.server import TServer # Make socket decorator_self._transport = TSocket.TSocket( host=dec_name, port=decorator_self._port) # Buffering is critical. Raw sockets are very slow num_retried = 0 while not decorator_self._transport.isOpen(): num_retried += 1 try: decorator_self._transport.open() decorator_self._transport = TTransport.TBufferedTransport( self._transport) except TTransport.TTransportException: logging.debug("Failed to get connection, sleeping: " + dec_name) sleep(10) logging.debug("Failed to get connection, retrying:" + dec_name) if num_retried > decorator_self._num_retries > 0: raise ValueError( "Maximum connection retries exceeded: ({0})". format(dec_name)) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(self._transport) # Create a client to use the protocol encoder client = decorator_self._thrift_class.Client(protocol) logging.debug("Client (" + dec_name + ") connected to server: " + str(self._transport.isOpen())) return client else: logging.debug("Returning Singleton of class: " + dec_name) return Singleton(original_clazz).Instance(*args, **kwargs)
from idls.is_idl.image_searcher.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TCompactProtocol from thrift.server import TServer # my custom utility from util.util import * from is_handler import ImageSearcherServiceHandler ishandler = ImageSearcherServiceHandler(is_conf, islogger) isprocessor = ImageSearcherService.Processor(ishandler) is_ip = is_conf["services"]["is"]["ip"] is_port = is_conf["services"]["is"]["port"] istransport = TSocket.TServerSocket(is_ip, is_port) istfactory = TTransport.TBufferedTransportFactory() ispfactory = TCompactProtocol.TCompactProtocolFactory() is_server = TServer.TSimpleServer(isprocessor, istransport, istfactory, ispfactory) islogger.info( "=================================================================") islogger.info("Starting Search Plan in ip \"{}\" and port {}".format( is_ip, is_port)) is_server.serve() islogger.info("Done")
def sendEmailMessage(self, email, message): print "sending email message, email: " + email + ", msg: " + message messageObj = MIMEText(message, "plain", "utf-8") messageObj['From'] = sender messageObj['To'] = email messageObj['Subject'] = Header('Message From Alpha-RPC', 'utf-8') try: smtpObj = smtplib.SMTP('smpt.163.com') smtpObj.login(sender, authCode) smtpObj.sendmail(sender, [email], messageObj.as_string()) print 'send mail success.' return True except smtplib.SMTPException, ex: print 'send mail failed.' print ex return False if __name__ == '__main__': handler = MessageServiceHandler() processor = MessageService.Processor(handler) transport = TSocket.TServerSocket("localhost", "9090") transportFactory = TTransport.TFramedTransportFactory() protocolFactory = TBinaryProtocal.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, transportFactory, protocolFactory) print "==========python thrift server start." server.serve() print "==========python thrift server exit."
result = Result() result.result = num1 + num2 return result def Subtract(self, num1, num2): result = Result() result.result = num1 - num2 return result def Multiply(self, num1, num2): result = Result() result.result = num1 * num2 return result def Divide(self, num1, num2): result = Result() if num2 == 0: result.message = "Impossible to divide by zero." else: result.result = num1 / num2 return result if __name__ == "__main__": serverTransport = TSocket.TServerSocket(port=5000) processor = CalculatorService.Processor(CalculatorServiceHandler()) server = TServer.TSimpleServer(processor, serverTransport) print(">> Starting service...") server.serve() print(">> Calculator Service Thrift started.")
# Add additional classes and functions here if needed if __name__ == "__main__": if len(sys.argv) < 3: print "Invocation <executable> <config_file> <id>" exit(-1) config_path = sys.argv[1] my_id = sys.argv[2] print "Initializing metadata server" handler = MetadataServerHandler(config_path, my_id) metaPort = handler.readServerPort() # Define parameters for thrift server processor = MetadataServerService.Processor(handler) transport = TSocket.TServerSocket(port=metaPort) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() # Create a server object server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print "Starting server on port : ", metaPort try: server.serve() except (Exception, KeyboardInterrupt) as e: print "\nExecption / Keyboard interrupt occured: ", e exit(0)
from thrift.protocol import TBinaryProtocol from thrift.transport import TSocket, TTransport from thrift.server import TServer __HOST = '127.0.0.1' __PORT = '8080' class empServiceHandler(object): # 注释 def getEmpByName(self, name): return ttypes.empModel def getEmpByeMisNo(self, mis): return ttypes.empModel if __name__ == '__main__': handler = empServiceHandler() process = empService.Processor(handler) trans = TSocket.TServerSocket(__HOST, __PORT) tfact = TTransport.TBufferedTransportFactory() pfact = TBinaryProtocol.TBinaryProtocolFactory() rpcserv = TServer.TSimpleServer(process, trans, tfact, pfact) print('Starting rpc server at ', __PORT, ':', __HOST) rpcserv.serve()