当前位置: 首页>>代码示例>>Python>>正文


Python TSocket.open方法代码示例

本文整理汇总了Python中thrift.transport.TSocket.TSocket.open方法的典型用法代码示例。如果您正苦于以下问题:Python TSocket.open方法的具体用法?Python TSocket.open怎么用?Python TSocket.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在thrift.transport.TSocket.TSocket的用法示例。


在下文中一共展示了TSocket.open方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_fast_transport

# 需要导入模块: from thrift.transport.TSocket import TSocket [as 别名]
# 或者: from thrift.transport.TSocket.TSocket import open [as 别名]
def get_fast_transport(endpoint, timeout=5000):
    """
    采用cython实现的transport
    :param endpoint:
    :param timeout:
    :return:
    """
    global _fast_transport
    if not _fast_transport:
        if endpoint.find(":") != -1:
            hostport = endpoint.split(":")
            host = hostport[0]
            port = int(hostport[1])
            unix_socket = None
        else:
            host = None
            port = None
            unix_socket = endpoint


        socket = TSocket(host=host, port=port, unix_socket=unix_socket)
        socket.setTimeout(timeout)
        socket.open()

        _fast_transport = TCyFramedTransport(socket, maxIdleTime=1200) # 20分钟没有写数据,则重新打开transport

    return _fast_transport
开发者ID:wfxiang08,项目名称:rpc_proxy_python,代码行数:29,代码来源:utils.py

示例2: connection_to_lb

# 需要导入模块: from thrift.transport.TSocket import TSocket [as 别名]
# 或者: from thrift.transport.TSocket.TSocket import open [as 别名]
    def connection_to_lb(self):
        if self.unix_socket:
            info_logger.info("Prepare open a socket to lb: %s, pid: %s", self.unix_socket, self.pid)
        else:
            info_logger.info("Prepare open a socket to lb: %s:%s, pid: %s", self.host, self.port, self.pid)

        # 1. 创建一个到lb的连接,然后开始读取Frame, 并且返回数据
        socket = TSocket(host=self.host, port=self.port, unix_socket=self.unix_socket)

        try:
            if not socket.isOpen():
                socket.open()
            socket.setTimeout(5000) # 出现异常,会自己重启
        except TTransportException:
            info_logger.info("Sleep %ds for another retry, pid: %s", self.reconnect_interval, self.pid)
            time.sleep(self.reconnect_interval)
            print_exception(info_logger)

            if self.reconnect_interval < 4:
                self.reconnect_interval *= 2
            return

        # 2. 连接创建成功
        self.reconnect_interval = 1

        self.socket = socket

        # 每次建立连接都重新构建
        self.queue = gevent.queue.Queue()
        self.connection_ok = True

        info_logger.info("Begin request loop....")
        # 3. 在同一个transport上进行读写数据
        transport = TCyFramedTransportEx(socket)

        #
        # 关注 transport的接口:
        #      flush_frame_buff
        #      read_frame
        #
        g1 = gevent.spawn(self.loop_reader, transport, self.queue)
        g2 = gevent.spawn(self.loop_writer, transport, self.queue)
        g3 = gevent.spawn(self.loop_hb_detect, transport)
        gevent.joinall([g1, g2, g3])


        # 4. 关闭连接
        try:
            # 什么情况下会关闭呢? 连接断开了,
            print time.strftime(ISOTIMEFORMAT, time.localtime()), "Trans Closed, queue size: ", self.queue.qsize(), ", pid: ", self.pid
            self.queue = None
            self.socket = None
            transport.close() # 关闭transport(而且transport也不会继续复用)
        except:
            print_exception(info_logger)
            pass
开发者ID:wfxiang08,项目名称:rpc_proxy_python,代码行数:58,代码来源:worker.py

示例3: _create_conn

# 需要导入模块: from thrift.transport.TSocket import TSocket [as 别名]
# 或者: from thrift.transport.TSocket.TSocket import open [as 别名]
    def _create_conn(self):
        self._host_index += 1
        self._host_index %= len(self._host_list)
        host = self._host_list[self._host_index]
        parts = host.split(':')
        host = parts[0]
        port = int(parts[1])

        conn = TSocket(host, port)
        conn.setTimeout(self._time_out)
        conn.open()
        return conn
开发者ID:haogods,项目名称:etl_task,代码行数:14,代码来源:base_client.py

示例4: TSocket

# 需要导入模块: from thrift.transport.TSocket import TSocket [as 别名]
# 或者: from thrift.transport.TSocket.TSocket import open [as 别名]
# 14-8-19
# create by: snower

import os
import sys

sys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))
sys.path.append(os.path.abspath(os.path.abspath(os.path.dirname(__file__))+os.sep+"gen-py"))

import time
from example.Example import Client
from thrift import Thrift
from thrift.transport.TSocket import TSocket
from thrift.transport.TTransport import TBufferedTransport
from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated

try:
    transport = TSocket('127.0.0.1', 20000)
    transport = TBufferedTransport(transport)
    protocol = TBinaryProtocolAccelerated(transport)
    client = Client(protocol)

    transport.open()

    start = time.time()
    for i in range(10000):
        result = client.add(0,i)
    print(time.time()-start)

except Thrift.TException as ex:
    print("%s" % (ex.message))
开发者ID:snower,项目名称:TorThrift,代码行数:33,代码来源:client.py

示例5: Dino

# 需要导入模块: from thrift.transport.TSocket import TSocket [as 别名]
# 或者: from thrift.transport.TSocket.TSocket import open [as 别名]

#.........这里部分代码省略.........
        if self.state.size > 5 and expected_calories_cost < 0.5 * self.state.calories:
            self.logger.info("Laying offspring!")
            direction = choice([0, 2, 4, 6])
            er = self.egg(direction, OFFSPRING_DONATION)
            if er.succeeded:
                self.logger.info("Successfully layed an egg!")
                self.state = er.parentDinoState
                self.logger.info("STATE: %s" % self.state)
                rc = Direction._RELATIVE_COORDINATES[direction]
                p = self.position + Coordinate(rc[1], rc[0])
                EGG_POOL.add((er.eggID, p.column, p.row))
                new_dir = choice(list(set([0, 2, 4, 6]) - set([direction,])))
                # Stupidly go away...
                for i in range(5):
                    self.move(new_dir)
                self.look(new_dir)
                self.counters['actions'] += 1
                self.counters['eggs'] += 1
                self.counters['calories_burnt'] += expected_calories_cost
            self.logger.info("LAY: %s" % er.message)

    def showPMReport(self):
        self.logger.info("PMR: size=%d" % self.state.size)
        self.logger.info("PMR: calories=%d, burnt=%d, found=%d, ratio=%f" % (self.state.calories,
                                                                             self.counters['calories_burnt'],
                                                                             self.counters['calories_found'],
                                                                             self.counters['calories_found'] != 0 and self.counters['calories_burnt']/self.counters['calories_found'] or -1))
        self.logger.info("PMR: moves=%d, looks=%d, eggs=%d, actions=%d" % (self.counters['moves'],
                                                                           self.counters['looks'],
                                                                           self.counters['eggs'],
                                                                           self.counters['actions']))

    def run(self):
        self.logger.info("Dino %s starting..." % self.name)
        self.transport.open()
        self.logger.info("Transport open.")
        if self.eggID is None:
            self.logger.info("I am the first egg. Registering.")
            rcr = self.registerClient(EMAIL, SCORE_NAME, ENTITY)
            self.logger.debug(rcr)
            for l in rcr.message.split("*"):
                self.logger.info("MESSAGE: %s" % l)
            self.species = rcr.species
            self.eggID = rcr.eggID
            self.logger.info("Got an eggID: %s" % self.eggID)
        self.state = self.hatch(self.eggID)
        self.logger.info("STATE: %s" % self.state)

        # Real algo here...

        try:
            while True:
                self.growIfWise()
                # Looking around
                direction = choice(range(8))
                self.logger.info("Looking %s" % Direction._VALUES_TO_NAMES[direction])
                self.look(direction)
                candidates = MAP_MANAGER.findClosest(self.position, EntityType.PLANT)
                if candidates is not None and len(candidates) > 0:
                    if candidates[0].coordinate.distance(self.position)*self.state.moveCost > 0.5*self.state.calories:
                        self.look(choice(list(set(range(8)) - getCone(direction, 2))))
                        candidates = MAP_MANAGER.findClosest(self.position, EntityType.PLANT)
                else:
                    self.logger.warning("No candidates found. Moving on...")
                    continue
                while candidates is not None and len(candidates) > 0:
                    a = candidates.pop(0)
                    self.logger.info("FOUND closest at %d, species='%s', size=%d" % (a.coordinate.distance(self.position),
                                                                                     a.species,
                                                                                     a.size))
                    if a.size > self.state.size + 2:
                        self.logger.info("Seems big! Discarding")
                        continue
                    if not self.moveTo(a.coordinate):
                        self.look(choice(range(8)))
                    elif self.counters['moves'] % 10 == 0:
                        self.logger.info("Random look")
                        self.look(choice(range(8)))
                    self.layIfWise()
                    self.growIfWise()
                    candidates = MAP_MANAGER.findClosest(self.position, EntityType.PLANT)
                    if candidates is not None and len(candidates) > 0:
                        if candidates[0].coordinate.distance(self.position)*self.state.moveCost > 0.5*self.state.calories:
                            self.look(choice(list(set(range(8)) - getCone(direction, 2))))
                            candidates = MAP_MANAGER.findClosest(self.position, EntityType.PLANT)
                    else:
                        self.logger.warning("No candidates found. Moving on...")
                        break
        except YouAreDeadException, e:
            self.logger.debug(e)
            self.logger.warning("DEAD: %s" % e.description)
        except GameOverException, e:
            global END_SCORE, BEST_SCORE
            self.logger.debug(e)
            self.logger.error("GameOver! won=%s, score=%d" % (e.wonGame, e.score))
            self.logger.info("HighScoreTable:")
            for l in e.highScoreTable.splitlines():
                self.logger.info(l)
            END_SCORE = e.score
            BEST_SCORE = [int(l.split()[-1]) for l in e.highScoreTable.splitlines() if SCORE_NAME in l][0]
开发者ID:nstinus,项目名称:dinoisland,代码行数:104,代码来源:dino.py


注:本文中的thrift.transport.TSocket.TSocket.open方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。