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


Python Socket.close方法代码示例

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


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

示例1: TestGeneralSocketMethods

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
class TestGeneralSocketMethods(unittest.TestCase):
    def setUp(self):
        self.socket = Socket(PAIR)

    def tearDown(self):
        self.socket.close()

    def test_bind(self):
        endpoint = self.socket.bind(SOCKET_ADDRESS)

        self.assertNotEqual(None, endpoint)

    def test_connect(self):
        endpoint = self.socket.connect(SOCKET_ADDRESS)

        self.assertNotEqual(None, endpoint)

    def test_is_open_is_true_when_open(self):
        self.assertTrue(self.socket.is_open())

    def test_is_open_is_false_when_closed(self):
        self.socket.close()

        self.assertFalse(self.socket.is_open())

    def test_set_and_get_int_option(self):
        expected = 500

        self.socket.set_int_option(SOL_SOCKET, SNDBUF, expected)

        actual = self.socket.get_int_option(SOL_SOCKET, SNDBUF)
        self.assertEqual(expected, actual)
开发者ID:codypiersall,项目名称:nanomsg-python,代码行数:34,代码来源:test_general_socket_methods.py

示例2: nano_server

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
def nano_server(endpoint):
    s = Socket(PAIR)
    s.bind('ipc://' + endpoint)
    #s.bind('tcp://127.0.0.1:9001')
    try:
        while True:
            s.recv()
            s.send('ok')
    finally:
        s.close()
开发者ID:LatitudeEngineering,项目名称:pmux,代码行数:12,代码来源:perf_nanomsg.py

示例3: NanomsgSubscriber

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
class NanomsgSubscriber(HiddenSubscriber):
    """ Subscriber class subscribing to a certain topic

        Attributes:
           context (zmq.Context):
           socket (Socket): Socket object of ZMQ context
           topic (String): Topic subscriber subscribes to
    """
    def __init__(self, url, topic):
        """ Initializes object

            Args:
                url (String): url to publish messages to
                topic (String): Topic to publish messages under
        """
        super(NanomsgSubscriber, self).__init__(topic)
        self._socket = Socket(SUB)
        self._socket.recv_timeout = 500 # Wait 500ms for receiving msgs
        self._socket.connect(url)
        self._socket.set_string_option(SUB, SUB_SUBSCRIBE, topic + '|')
        self._logger = logging.getLogger('NanomsgSubscriber')

    def receive(self):
        """ Receives a message

            Returns:
                String
        """
        message = self._socket.recv()
        return message[len(self.topic) + 1:]

    def __enter__(self):
        """ Statement used for the `` with ... as ...:`` returns
            the object to use in the ``with`` block

            Returns:
                NanomsgSubscriber
        """
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        """ Executed when leaving ``with`` block, regardless whether
            because of an exception or normal program flow
        """
        self._socket.close()
开发者ID:PaddyK,项目名称:biosi,代码行数:47,代码来源:nanomsgcomponents.py

示例4: ConsoleProxy

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
class ConsoleProxy(object):
    def __init__(self, url, recv_timeout=1000, send_timeout=1000):
        self.url = url.encode()
        self.socket = Socket(REQ)

        self.socket.recv_timeout = recv_timeout
        self.socket.send_timeout = send_timeout

        super(ConsoleProxy, self).__init__()

    def connect(self):
        self.socket.connect(self.url)

    def disconnect(self):
        self.socket.close()

    def send_command(self, cmd_name, echo=True, **kwargs):
        command = {
            "name": cmd_name,
            "args": kwargs
        }

        dump = msgpack.packb(command)

        if echo:
            print('send: ', command)

        try:
            self.socket.send(dump)
        except NanoMsgAPIError as e:
            print('send_error', e.msg)
            pass

        try:
            recv = self.socket.recv()
            unpack_msg = msgpack.unpackb(recv, encoding='utf-8')

            if echo:
                print('recv: ', recv)
                print(unpack_msg)

            return unpack_msg
        except NanoMsgAPIError as e:
            print('recv_error', e.msg)
开发者ID:cyberegoorg,项目名称:cetech,代码行数:46,代码来源:consoleproxy.py

示例5: NanomsgPublisher

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
class NanomsgPublisher(HiddenPublisher):
    """ Publisher class publishing messages to a certain topic to an url

        Attributes:
            context (zmq.Context):
            socket (Socket): Socket object of ZMQ context
            topic (String): Topic publisher publishs to
    """
    def __init__(self, url, topic):
        """ Initializes object

            Args:
                url (String): url to publish messages to
                topic (String): Topic to publish messages under
        """
        super(NanomsgPublisher, self).__init__(topic)
        self._socket = Socket(PUB)
        self._socket.send_timeout = 1 # Wait 1ms for sending
        self._socket.bind(url)
        self._logger = logging.getLogger('NanomsgPublisher')

    def publish(self, message):
        """ Publishes message

            Args:
                message (String): Message to publish
        """
        self._socket.send('{}|{}'.format(self._topic, message))

    def __enter__(self):
        """ Statement used for the `` with ... as ...:`` returns
            the object to use in the ``with`` block

            Returns:
                NanomsgPublisher
        """
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        """ Executed when leaving ``with`` block, regardless whether
            because of an exception or normal program flow
        """
        self._socket.close()
开发者ID:PaddyK,项目名称:biosi,代码行数:45,代码来源:nanomsgcomponents.py

示例6: main

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
def main():
    sift_root = init.env_var_or_exit('SIFT_ROOT')
    ipc_root = init.env_var_or_exit('IPC_ROOT')
    dag = load_dag(sift_root)
    threads = {}
    sockets = []
    node_indexes = sys.argv[1:]
    if len(node_indexes) == 0:
        print('no nodes to execute')
        return 1

    dry = os.environ.get('DRY', 'false')
    if dry == 'true':
        return 0

    for i in map(int, node_indexes):
        src = os.path.join(sift_root, dag['dag']['nodes'][i]['implementation']['python'])
        print('loading ' + src)
        m = new_module(i, src)

        # Create nanomsg socket.
        addr = 'ipc://%s/%d.sock'% (ipc_root, i)
        s = Socket(REP)
        s.recv_max_size = -1
        s.connect(addr)
        print('connected to '+ addr)
        sockets.append(s)

        # Launch request handler.
        t = threading.Thread(target=listen_and_reply, args=(s, m.compute))
        t.daemon = True
        t.start()
        threads[i] = t

    try:
        while True:
            time.sleep(1)
            for i, thr in threads.items():
                if not thr.isAlive():
                    raise Exception('thread of node with index %d is dead' % i)
    finally:
        print('closing sockets')
        for s in sockets: s.close()
开发者ID:redsift,项目名称:sandbox-python,代码行数:45,代码来源:run.py

示例7: Client

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
class Client(Common):
    def __init__(self, uri="inproc://server", id=None):
        self.sock = Socket(REQ)
        self.sock.connect(uri)
        self.id = id

    def close(self):
        self.sock.close()

    def call(self, func, *args):
        msg = self.dump((func, args))
        self.sock.send(msg)
        return self.load(self.sock.recv())

    def sync_call(self, func, *args):
        id = self.call(func, *args)
        print "got id", id
        while True:
            res = self.getresult(id)
            if res:
                return res
            time.sleep(0.1)

    def result(self, id, result):
        return self.call("result", id, result)

    def getresult(self, id):
        return self.call("getresult", id)

    def getstate(self, key):
        return self.call("getstate", key)

    def setstate(self, key, value):
        return self.call("setstate", key, value)

    def getlog(self, id, since=0):
        return self.call("getlog", id, since)

    def out(self, msg):
        return self.call("out", self.id, msg)

    def err(self, msg):
        return self.call("err", self.id, msg)
开发者ID:JustinAzoff,项目名称:apitest,代码行数:45,代码来源:app.py

示例8: ServiceDiscovery

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
class ServiceDiscovery(object):
 
    def __init__(self, port, deadline=5000):
        self.socket = Socket(SURVEYOR)
        self.port = port
        self.deadline = deadline
        self.services = defaultdict(set)
 
    def bind(self):
        self.socket.bind('tcp://172.30.42.174:%s' % self.port)
        self.socket.set_int_option(SURVEYOR, SURVEYOR_DEADLINE, self.deadline)
 
    def discover(self):
        if not self.socket.is_open():
            return self.services
 
        self.services = defaultdict(set)
        self.socket.send('service query')
 
        while True:
            try:
                response = self.socket.recv()
            except NanoMsgAPIError:
                break
 
            service, address = response.split('|')
            self.services[service].add(address)
 
        return self.services
 
    def resolve(self, service):
        providers = self.services[service]
 
        if not providers:
            return None
 
        return random.choice(tuple(providers))
 
    def close(self):
        self.socket.close()
开发者ID:marchon,项目名称:upush,代码行数:42,代码来源:NanoServiceDiscovery.py

示例9: nano_client

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
def nano_client(endpoint):
    s = Socket(PAIR)
    s.connect('ipc://' + endpoint)
    #s.connect('tcp://127.0.0.1:9001')
    count = 0

    payload = test_str(SIZE)

    start = time.time()
    try:
        while True:
            s.send(payload)
            s.recv()
            count += 1
    except:
        pass
    finally:
        end = time.time()
        total = end - start
        print 'total: ', count
        print 'took: ', total
        print 'req / sec:', count / total
        print 'bandwidth: %f MBps' % (((count / total) * SIZE) / 2 ** 20)
        s.close()
开发者ID:LatitudeEngineering,项目名称:pmux,代码行数:26,代码来源:perf_nanomsg.py

示例10: Socket

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import close [as 别名]
from __future__ import print_function
from nanomsg import Socket, PAIR, PUB

s1 = Socket(PAIR)
s2 = Socket(PAIR)
s1.bind('inproc://bob')
s2.connect('inproc://bob')
s1.send(b'hello nanomsg')
print(s2.recv())
s1.close()
s2.close()



with Socket(PAIR) as s3:
	with Socket(PAIR) as s4:
		s3.bind('inproc://demo')
		s4.connect('inproc://demo')
		s3.send('hi, I use "with"')
		print(s4.recv())
		s4.send('Ok, I see.')
		print(s3.recv())


开发者ID:Wingman639,项目名称:python_tips,代码行数:24,代码来源:nanomsg_pair.py


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