def run(manage_port, accounts_port): try: transport_manage = TSocket.TSocket('localhost', manage_port) # Buffering is critical. Raw sockets are very slow transport_manage = TTransport.TBufferedTransport(transport_manage) # Wrap in a protocol protocol_manage = TBinaryProtocol.TBinaryProtocol(transport_manage) # Create a client to use the protocol encoder client_manage = ManageService.Client(protocol_manage) # Connect! transport_manage.open() transport_accounts = TSocket.TSocket('localhost', accounts_port) transport_accounts = TTransport.TBufferedTransport(transport_accounts) standard_protocol = TMultiplexedProtocol( TBinaryProtocol.TBinaryProtocol(transport_accounts), "StandardService") premium_protocol = TMultiplexedProtocol( TBinaryProtocol.TBinaryProtocol(transport_accounts), "PremiumService") client_premium = PremiumService.Client(premium_protocol) client_standard = StandardService.Client(standard_protocol) transport_accounts.open() try: client_info = client_manage.getAccount( ClientData('K', 'K', '900', 10000)) print(client_info) except FailedToCreateException: pass password = '******' credit_info = client_premium.getCredit( '900', hashlib.sha3_256(password.encode()).hexdigest(), 10, MonetaryType(1000, 0), getattr(CurrencyName, 'EUR')) print(credit_info) shell_loop(client_manage, client_standard, client_premium) transport_manage.close() transport_accounts.close() except Thrift.TException as tx: print('%s' % (tx.message))
def connect_to_thrift(conf): """ Connect to a thrift endpoint as determined by the 'conf' parameter. Note that this does *not* open the transport. Returns a tuple of (service, protocol, transport) """ if conf.transport_mode == 'http': mode = THttpClient(conf.http_url) mode.set_verify(conf.validate) else: if conf.use_ssl: try: from ssl import PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: try: from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 mode = TSSLSocketWithWildcardSAN(conf.host, conf.port, validate=conf.validate, ca_certs=conf.ca_certs, keyfile=conf.keyfile, certfile=conf.certfile, ssl_version=PROTOCOL_SSLv23) else: mode = TSocket(conf.host, conf.port) if conf.timeout_seconds: # Thrift trivia: You can do this after the fact with # _grab_transport_from_wrapper(self.wrapped.transport).setTimeout(seconds*1000) mode.setTimeout(conf.timeout_seconds * 1000.0) if conf.transport_mode == 'http': if conf.use_sasl and conf.mechanism != 'PLAIN': mode.set_kerberos_auth(service=conf.kerberos_principal) else: mode.set_basic_auth(conf.username, conf.password) if conf.transport_mode == 'socket' and conf.use_sasl: def sasl_factory(): saslc = sasl.Client() saslc.setAttr("host", str(conf.host)) saslc.setAttr("service", str(conf.kerberos_principal)) if conf.mechanism == 'PLAIN': saslc.setAttr("username", str(conf.username)) saslc.setAttr("password", str(conf.password)) # Defaults to 'hue' for a non-empty string unless using LDAP else: saslc.setAttr("maxbufsize", SASL_MAX_BUFFER.get()) saslc.init() return saslc transport = TSaslClientTransport(sasl_factory, conf.mechanism, mode) elif conf.transport == 'framed': transport = TFramedTransport(mode) else: transport = TBufferedTransport(mode) protocol = TBinaryProtocol(transport) if conf.multiple: protocol = TMultiplexedProtocol(protocol, conf.service_name) service = conf.klass(protocol) return service, protocol, transport
def load_service_client(self, service_name): if service_name not in self.__service_bind_map: raise Exception( 'service {} must bind service_module thrift generated.'.format( service_name)) service_module = self.__service_bind_map[service_name] # 获取可用的服务 host, port = self.__zk_for_client.load_available_service(service_name) print('we load service {} from {}:{}'.format(service_name, host, port)) socket = TSocket.TSocket(host, port) transport = None try: # 获取Transport transport = TTransport.TBufferedTransport(socket) # 获取TBinaryProtocol protocol = TBinaryProtocol.TBinaryProtocol(transport) service_protocol = TMultiplexedProtocol(protocol, service_name) # 获取该service的客户端对象 client = service_module.Client(service_protocol) # 连接通道transport transport.open() yield client except Thrift.TException as ex: print('%s' % (ex.message)) finally: if transport: # 关闭通道transport transport.close()
def main(): addr = "112.74.23.141" port = 6000 print("Linking to: %s:%s" % (addr, port)) transport = TSocket.TSocket(addr, port) # Buffering is critical, Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) ocr_protocol = TMultiplexedProtocol(protocol, "ocr_server") result_protocol = TMultiplexedProtocol(protocol, "result_server") # Create a client to use the protocol encoder ocr_client = ocr_server.Client(ocr_protocol) result_client = result_server.Client(result_protocol) while (1): start = time.time() try: transport.open() images = ocr_client.line_ocr() img_list = save_img(images) ocr_results = [] img_list.sort() for img in img_list: ocr_rlt = ocr.ocr(img["full_path"]) print ocr_rlt rlt = ocr_result(img_name=img["img_name"], result=ocr_rlt) ocr_results.append(rlt) if len(img_list) != 0: result_client.write_ocr_result(ocr_results) transport.close() print("ocr's time:%f" % (time.time() - start)) except Exception: #except thrift.TTransportException, tx: print("Failed to connect to %s:%d" % (addr, port)) time.sleep(1)
def start(self): self.transport = connect( TTransport.TFramedTransport( TSocket.TSocket(self.master_host, self.rpc_port)), self.rpc_max_retries, self.rpc_retry_interval / 1000) # Set client to our Example self.client = DistributedFilesystem.Client( TMultiplexedProtocol( TBinaryProtocol.TBinaryProtocol(self.transport), "DFSService"))
def connect_to_thrift(conf): """ Connect to a thrift endpoint as determined by the 'conf' parameter. Note that this does *not* open the transport. Returns a tuple of (service, protocol, transport) """ if conf.use_ssl: sock = TSSLSocket(conf.host, conf.port, validate=conf.validate, ca_certs=conf.ca_certs, keyfile=conf.keyfile, certfile=conf.certfile) else: sock = TSocket(conf.host, conf.port) if conf.timeout_seconds: # Thrift trivia: You can do this after the fact with # _grab_transport_from_wrapper(self.wrapped.transport).setTimeout(seconds*1000) sock.setTimeout(conf.timeout_seconds * 1000.0) if conf.transport_mode == 'http': sock = THttpClient(conf.http_url, cert_validate=conf.validate) if conf.use_sasl and conf.mechanism != 'PLAIN': sock.set_kerberos_auth() else: sock.set_basic_auth(conf.username, conf.password) transport = TBufferedTransport(sock) elif conf.use_sasl: def sasl_factory(): saslc = sasl.Client() saslc.setAttr("host", str(conf.host)) saslc.setAttr("service", str(conf.kerberos_principal)) if conf.mechanism == 'PLAIN': saslc.setAttr("username", str(conf.username)) saslc.setAttr( "password", str(conf.password) ) # defaults to hue for a non-empty string unless using ldap saslc.init() return saslc transport = TSaslClientTransport(sasl_factory, conf.mechanism, sock) elif conf.transport_mode == 'framed': transport = TFramedTransport(sock) else: transport = TBufferedTransport(sock) protocol = TBinaryProtocol(transport) if conf.multiple: protocol = TMultiplexedProtocol(protocol, conf.service_name) service = conf.klass(protocol) return service, protocol, transport
def launch(self): transport = TTransport.TBufferedTransport( TSocket.TSocket('localhost', self.bank_port)) transport.open() protocol = TBinaryProtocol.TBinaryProtocol(transport) self.account_management = AccountManagment.Client( TMultiplexedProtocol(protocol, "AccountManagementService")) self.standard_management = StandardManagement.Client( TMultiplexedProtocol(protocol, "StandardManagementService")) self.premium_management = PremiumManagement.Client( TMultiplexedProtocol(protocol, "PremiumManagementService")) print("Client started, bank port: " + str(self.bank_port)) self.start() transport.close()
def get_protocol(service_name): transport = TSocket.TSocket('127.0.0.1', 9999) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) defined_protocol = TMultiplexedProtocol(protocol, service_name) transport.open() #打开链接 time.sleep(0.5) if transport.isOpen(): connect_handler = ConnectServiceNoneHandler() conn_processor = ConnectService.Processor(connect_handler) if conn_processor.process(protocol, protocol): return defined_protocol return None
def Init(self): try: socket = TSocket.TSocket(self.host, self.port) transport = TTransport.TFramedTransport(socket) protocol = TBinaryProtocol.TBinaryProtocol(transport) protocol_multi = TMultiplexedProtocol(protocol, "Feature Service") client = FeatureService.Client(protocol_multi) transport.open() self.client = client #print("connect success") return True except Exception, e: print("InitClient exception:%s" % e) return False
def main(port): # Make socket transport = TSocket.TSocket('localhost', port) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a client to use the protocol encoder bank_manager = BankManager.Client(TMultiplexedProtocol(protocol, "Manager")) bank_standard = BankStandard.Client(TMultiplexedProtocol(protocol, "Standard")) bank_premium = BankPremium.Client(TMultiplexedProtocol(protocol, "Premium")) # Connect! transport.open() print("[CLIENT STARTED] Port: " + str(port)) account_management_loop(bank_manager, bank_standard, bank_premium) # Close! transport.close()
def main(): # 以frame为单位进行传输,非阻塞式服务中使用 transport = TTransport.TFramedTransport( TSocket.TSocket(host="127.0.0.1", port=9999)) transport.open() # 序列化方式 protocol = TBinaryProtocol.TBinaryProtocol(transport) multiplexedprotocol = TMultiplexedProtocol(protocol, "calService") client = Calculator.Client(multiplexedprotocol) param = CalParam(num1=1, num2=2, op=Operation.ADD) re = client.getResult(param) print(param) print(re) transport.close()
def _connect(self): if self.path is None: self._socket = TSocket(self.host, self.port) else: self._socket = THttpClient(self._makeConnectURI()) self._socket.setTimeout(int(self.connect_timeout * 1000)) self._transport = self.transport_class(self._socket) self._protocol = self.protocol_class(self._transport) if self.multiplex_service is not None: self._protocol = TMultiplexedProtocol( self._protocol, self.multiplex_service, ) self._client = self.module.Client(self._protocol) self._transport.open()
def cmd_server_process(): try: transport = TSocket.TSocket('127.0.0.1', 9999) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) mul_protocol = TMultiplexedProtocol(protocol, "ConnectService") connect_handler = ConnectServiceHandler(mul_protocol) conn_processor = ConnectService.Processor(connect_handler) transport.open() #打开链接 #startThreadService(cmd_client_process, mul_protocol, cmdstr="TestCmd") while True: conn_processor.process(protocol, protocol) except TTransport.TTransportException as tx: print("cmd_server_process Error TTransport.TTransportException == {}". format(tx)) except Exception as x: print("Error Exeption == {}".format(x))
def __init__(self): self.configuration = TanitConfiguration.getInstance() master_host = self.configuration.get(Keys.MASTER_HOSTNAME) if master_host is None: raise TanitConfigurationException( "Missing required configuration '%s'", Keys.MASTER_HOSTNAME) rpc_port = self.configuration.get_int(Keys.MASTER_RPC_PORT) if rpc_port is None: raise TanitConfigurationException( "Missing required configuration '%s'", Keys.MASTER_RPC_PORT) self.transport = TTransport.TFramedTransport( TSocket.TSocket(master_host, rpc_port)) self.client = MasterUserService.Client( TMultiplexedProtocol( TBinaryProtocol.TBinaryProtocol(self.transport), "UserService"))
def thriftInterface(socketIp, intSocket, version, dataid, exceldata, outcheck, outresult, adic, api, reportObj, report_row): interfaceResult = True inputResult = inputDataOprate(exceldata, adic) if not inputResult: return False transport = TSocket.TSocket(socketIp, intSocket) transport = TTransport.TBufferedTransport(transport) protocol = TCompactProtocol.TCompactProtocol(transport) p = TMultiplexedProtocol(protocol, "bkt") client = Bkt.Client(p) transport.open() request = Request() request.api = api request.version = version request.data = json.dumps(adic, ensure_ascii=False) try: output = client.api(request) except Exception, e: reportObj.writeData(2, report_row, 1, adic) reportObj.writeData(2, report_row, 2, str(e._message).encode("utf-8")) if outcheck != None: message = str(outcheck).replace(":", ":").split(":=")[1] if message == e._message.encode("utf-8"): return True, "pass" log.Output( " [Failed]:%s expect is %s,real is %s" % ("message", message, str(e._message).encode("utf-8")), 'error') log.Output(" input:%s" % adic) log.Output(" thrift异常:%s" % str(e._message).encode("utf-8")) transport.close() return False, e
def create_tenant_profile_client(transport): protocol = get_binary_protocol(transport) multiplex_prot = TMultiplexedProtocol(protocol, TENANT_PROFILE_CPI_NAME) return TenantProfileService.Client(multiplex_prot)
def create_iamadmin_client(transport): protocol = get_binary_protocol(transport) multiplex_prot = TMultiplexedProtocol(protocol, IAM_ADMIN_SERVICES_CPI_NAME) return IamAdminServices.Client(multiplex_prot)
def create_group_manager_client(transport): protocol = get_binary_protocol(transport) multiplex_prot = TMultiplexedProtocol(protocol, GROUP_MANAGER_CPI_NAME) return GroupManagerService.Client(multiplex_prot)
def factory(transport): protocol = TBinaryProtocol.TBinaryProtocol(transport) multiplex_prot = TMultiplexedProtocol(protocol, cls.service_name) return multiplex_prot
def get_user_profile_client(protocol): multiplex_prot = TMultiplexedProtocol(protocol, USER_PROFILE_CPI_NAME) return UserProfileService.Client(multiplex_prot)
import sys, glob from thrift.protocol.TMultiplexedProtocol import TMultiplexedProtocol sys.path.append('gen-py') # sys.path.insert(0, glob.glob('../../lib/py/build/lib.*')[0]) from cn.jsfund.trading.quotation.module.realtime import RealTimeQuotationService from cn.jsfund.trading.quotation.module.realtime.ttypes import * from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TCompactProtocol transport = TSocket.TSocket('121.40.156.222', 9090) transport = TTransport.TBufferedTransport(transport) protocol = TCompactProtocol.TCompactProtocol(transport) p = TMultiplexedProtocol(protocol, "RealTimeQuotationService") # Create a client to use the protocol encoder client = RealTimeQuotationService.Client(p) transport.open() # quote = client.getSimpleQuotations('002441.SZ') quote = client.getSimpleQuotations('018001.SH') print quote # print client.getSimpleQuotations('601918.SH') print client.getSimpleQuotations('002131.SZ') print client.getSimpleQuotations('601918.SH') print client.getSimpleQuotations('600023.SH')
def get_iamadmin_client(protocol): multiplex_prot = TMultiplexedProtocol(protocol, IAM_ADMIN_SERVICES_CPI_NAME) return IamAdminServices.Client(multiplex_prot)
def get_group_manager_client(protocol): multiplex_prot = TMultiplexedProtocol(protocol, GROUP_MANAGER_CPI_NAME) return GroupManagerService.Client(multiplex_prot)
from thrift.protocol import TBinaryProtocol from thrift.protocol.TMultiplexedProtocol import TMultiplexedProtocol from thrift.transport import TSocket, TTransport from thrift_python.smarthome import SmartHome from handlers import SmartHomeClientHandler from utils import enable_logger import logging import time if __name__ == '__main__': enable_logger(filename="client") transport = TSocket.TSocket('localhost', 9090) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport, True, True) client = SmartHome.Client(TMultiplexedProtocol(protocol, "smart_home")) transport.open() devices = client.getDevicesIds() smart_home = SmartHomeClientHandler(devices, protocol) logging.info("Connected") time.sleep(0.1) smart_home.start()
import json from tutorial import Calculator, CcktvRoom from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.protocol.TMultiplexedProtocol import TMultiplexedProtocol transport = TSocket.TSocket('127.0.0.1', 8000) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) # 如果服务端使用TMultiplexedProcessor接收处理,客户端必须用TMultiplexedProtocol并且serviceName必须和服务端的一致 calculator_protocol = TMultiplexedProtocol(protocol, "calculator") ccktv_room_protocol = TMultiplexedProtocol(protocol, "ccktv_room") calc_client = Calculator.Client(calculator_protocol) room_client = CcktvRoom.Client(ccktv_room_protocol) transport.open() print( calc_client.invoke(1, '1111-2222-3333-4444', json.dumps({"name": "zhoujielun"}))) print(calc_client.sayMsg("avatar")) res = room_client.getBannerList({'1': '11'}, 10) print(res, type(res)) transport.close() # transport = TSocket.TSocket('127.0.0.1', 8000) # transport = TTransport.TBufferedTransport(transport) # protocol = TBinaryProtocol.TBinaryProtocol(transport)
def create_user_profile_client(transport): protocol = get_binary_protocol(transport) multiplex_prot = TMultiplexedProtocol(protocol, USER_PROFILE_CPI_NAME) return UserProfileService.Client(multiplex_prot)
def __init__(self, device_name, protocol): self.device_name = device_name self.protocol = protocol self.client = ModeLed.Client( TMultiplexedProtocol(self.protocol, self.device_name))
def get_tenant_profile_client(protocol): multiplex_prot = TMultiplexedProtocol(protocol, TENANT_PROFILE_CPI_NAME) return TenantProfileService.Client(multiplex_prot)
def __init__(self, device_name, protocol): self.device_name = device_name self.protocol = protocol self.client = VaccumRobotPro.Client( TMultiplexedProtocol(self.protocol, self.device_name))
def __init__(self, device_name, protocol): self.device_name = device_name self.protocol = protocol self.client = AirConditionPro.Client( TMultiplexedProtocol(self.protocol, self.device_name))