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


Python asyncio.open_connection方法代码示例

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


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

示例1: __connect

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def __connect(self, host, port):
        """ Retries until success """
        Logger.info("Trying to connect {}:{}".format(host, port))
        while True:
            try:
                reader, writer = await asyncio.open_connection(
                    host, port, loop=self.loop
                )
                break
            except Exception as e:
                Logger.info("Failed to connect {} {}: {}".format(host, port, e))
                await asyncio.sleep(
                    self.env.cluster_config.MASTER.MASTER_TO_SLAVE_CONNECT_RETRY_DELAY
                )
        Logger.info("Connected to {}:{}".format(host, port))
        return reader, writer 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:18,代码来源:master.py

示例2: test_bad_request_response

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def test_bad_request_response(app):
    lines = []

    @app.listener("after_server_start")
    async def _request(sanic, loop):
        connect = asyncio.open_connection("127.0.0.1", 42101)
        reader, writer = await connect
        writer.write(b"not http")
        while True:
            line = await reader.readline()
            if not line:
                break
            lines.append(line)
        app.stop()

    app.run(host="127.0.0.1", port=42101, debug=False)
    assert lines[0] == b"HTTP/1.1 400 Bad Request\r\n"
    assert b"Bad Request" in lines[-1] 
开发者ID:huge-success,项目名称:sanic,代码行数:20,代码来源:test_bad_request.py

示例3: bus_monitor

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def bus_monitor(receiver,
                      host='localhost',
                      port=6720,
                      decoder=telegram_decoder):
    """ creates a connection to host:port and starts to receive telegrams

    :param receiver: a coroutine or instance of a class that has a `send`
                     method which takes one argument to receive a telegram.
    :param host: hostname to which to connect to
    :param port: port to which to connect to
    :param decoder: optional alternative decoder to transform binary data into
                    telegrams

    received telegrams will be sent to the receiver.
    """
    reader, writer = await open_connection(host, port)
    await listen(reader, receiver, decoder)
    writer.close() 
开发者ID:mfussenegger,项目名称:knx,代码行数:20,代码来源:knx.py

示例4: tcp_connection

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def tcp_connection(address):
    """Async generator reading from tcp network transport layer"""
    logger = logging.getLogger('asyncio.tcp-connection')
    logger.debug('... connecting to tcp://{}:{}'.format(*address))
    reader, writer = await asyncio.open_connection(*address)
    try:
        while True:
            data = await reader.read(128)
            if data:
                logger.debug('<<< {!r}'.format(data))
                yield data
            else:
                break
    finally:
        logger.debug('... closing')
        writer.close()


# ============================================================================== 
开发者ID:nokia,项目名称:moler,代码行数:21,代码来源:network_down_detector.py

示例5: open

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def open(self):
        """Open TCP connection."""
        self._debug('connecting to {}'.format(self))
        # If a task is canceled while it is waiting for another concurrent operation,
        # the task is notified of its cancellation by having a CancelledError exception
        # raised at the point where it is waiting
        try:
            self._stream_reader, self._stream_writer = await asyncio.open_connection(host=self.host, port=self.port)
            # self._stream_reader, self._stream_writer = await asyncio.wait_for(asyncio.open_connection(host=self.host, port=self.port), timeout=10)
        except asyncio.CancelledError as err:
            self._debug("CancelledError while awaiting for open_connection({}), err: {}".format(self, err))
            # TODO: stop child task of asyncio.open_connection
            raise
        else:
            self.connection_lost = asyncio.Future()  # delayed to be created in same loop as open()
            asyncio.ensure_future(self.forward_connection_read_data())
        self._debug('connection {} is open'.format(self)) 
开发者ID:nokia,项目名称:moler,代码行数:19,代码来源:tcp.py

示例6: __connect

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def __connect(self):
        self.__check_closed()
        if self.connected:
            return
        try:
            self.logger.debug("Opening connection to %s:%d", self.host, self.port)
            future = asyncio.open_connection(self.host, self.port, loop=self.__loop)
            self.__reader, self.__writer = await asyncio.wait_for(
                future, timeout=self.connect_timeout, loop=self.__loop
            )

            await asyncio.wait_for(self.__connect_request_response(), timeout=self.request_timeout, loop=self.__loop)

            self.logger.debug("Socket connected successfully. Starting read loop.")
            self.connected = True
            self.__loop.create_task(self.__read_loop())
        except ConnectionError as e:
            self.logger.error("Connection error while connecting to server: %s", e)
            raise 
开发者ID:aws,项目名称:aws-greengrass-core-sdk-python,代码行数:21,代码来源:streammanagerclient.py

示例7: connect

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def connect(self):
        """Make a TCP connection to the alarm system."""
        _LOGGER.debug("Connecting...")

        try:
            self._reader, self._writer = await asyncio.open_connection(
                self._host, self._port, loop=self._loop)
            _LOGGER.debug("sucess connecting...")

        except Exception as e:
            _LOGGER.warning(
                "Exception during connecting: %s.", e)
            self._writer = None
            self._reader = None
            return False

        return True 
开发者ID:c-soft,项目名称:satel_integra,代码行数:19,代码来源:satel_integra.py

示例8: handle_ext_server_connection

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def handle_ext_server_connection(
        upstream_host: str,
        upstream_port: int,
        reader: asyncio.StreamReader,
        writer: asyncio.StreamWriter,
        info: adapters.ExtOrPortClientConnection,
) -> None:
    handler_logger.info('Connection received from %r', info)
    async with contexts.log_unhandled_exc(handler_logger), \
               contexts.aclosing_multiple_writers(writer) as writers:
        try:
            ureader, uwriter = await asyncio.open_connection(
                upstream_host, upstream_port)
        except OSError as e:
            handler_logger.warning(
                'Error while connecting to upstream: %r', e)
            return
        writers.add(writer)
        try:
            await relays.relay(reader, writer, ureader, uwriter)
        except OSError as e:
            handler_logger.warning('Connection from %r caught %r', info, e) 
开发者ID:twisteroidambassador,项目名称:ptadapter,代码行数:24,代码来源:console_script.py

示例9: test_reader_writer_echo

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def test_reader_writer_echo(loop, sock_pair):
    """Verify readers and writers can send data to each other."""
    c_sock, s_sock = sock_pair

    @asyncio.coroutine
    def mycoro():
        c_reader, c_writer = yield from asyncio.open_connection(sock=c_sock)
        s_reader, s_writer = yield from asyncio.open_connection(sock=s_sock)

        data = b'Echo... Echo... Echo...'
        s_writer.write(data)
        yield from s_writer.drain()
        read_data = yield from c_reader.readexactly(len(data))
        assert data == read_data
        s_writer.close()

    loop.run_until_complete(asyncio.wait_for(mycoro(), timeout=1.0)) 
开发者ID:gmarull,项目名称:asyncqt,代码行数:19,代码来源:test_qeventloop.py

示例10: connectTarget

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def connectTarget(self, addr, port, data):
        logging.info('requested %s <--> %s:%s' % (self.peer, addr, port))
        try:
            reader, writer = yield from open_connection(addr, port)
        except (ConnectionError, OSError, TimeoutError) as e:
            logging.info("can't connect to %s:%s (from %s)" % (addr, port, self.peer))
            return self.resetTunnel("can't connect to %s:%s" % (addr, port), str(e))
        self.setProxy(reader, writer)
        if data:
            writer.write(data)
        if self._dataToTarget:
            writer.write(self._dataToTarget)
            self._dataToTarget.clear()
        self.connectTargetTask = None

    # next 2 overrides deal with a implicit state which exists only in wstan server: CONNECTING
    # data received during CONNECTING will be sent after connected
    # IDLE --onConnect--> CONNECTING --connectTarget--> USING
    # CONNECTING --RST-received-and-RST-sent--> IDLE
    # CONNECTING --RST-sent--> RESETTING --RST-received--> IDLE 
开发者ID:krrr,项目名称:wstan,代码行数:22,代码来源:server.py

示例11: remote_sort

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def remote_sort():
    reader, writer = await asyncio.open_connection("127.0.0.1", 2015)
    print("Generating random list...")
    numbers = [random.randrange(10000) for r in range(10000)]
    data = json.dumps(numbers).encode()
    print("List Generated, Sending data")
    writer.write(len(data).to_bytes(8, "big"))
    writer.write(data)

    print("Waiting for data...")
    data = await reader.readexactly(len(data))
    print("Received data")
    sorted_values = json.loads(data.decode())
    print(sorted_values)
    print("\n")
    writer.close() 
开发者ID:PacktPublishing,项目名称:Python-3-Object-Oriented-Programming-Third-Edition,代码行数:18,代码来源:sort_client.py

示例12: create_connection

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def create_connection(repetitions):
    reader, writer = await asyncio.open_connection(
        host=HOST, port=PORT)

    start_time = float((await reader.readline()))

    writer.write(repetitions.encode() + b'\n')
    await writer.drain()

    async for line in reader:
        # Sleeping a little to emulate processing time and make
        # it easier to add more simultaneous clients
        await asyncio.sleep(1)

        printer(start_time, 'Got line: ', line.decode(),
                end='')

    writer.close() 
开发者ID:PacktPublishing,项目名称:Python-Journey-from-Novice-to-Expert,代码行数:20,代码来源:08_echo_server.py

示例13: remote_sort

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def remote_sort():
    reader, writer = yield from asyncio.open_connection('127.0.0.1', 2015)
    print("Generating random list...")
    numbers = [random.randrange(10000) for r in range(10000)]
    data = json.dumps(numbers).encode()
    print("List Generated, Sending data")
    writer.write(len(data).to_bytes(8, 'big'))
    writer.write(data)

    print("Waiting for data...")
    data = yield from reader.readexactly(len(data))
    print("Received data")
    sorted_values = json.loads(data.decode())
    print(sorted_values)
    print('\n')
    writer.close() 
开发者ID:PacktPublishing,项目名称:Python-Journey-from-Novice-to-Expert,代码行数:18,代码来源:13_10_async_client.py

示例14: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def __init__(self, *, socket_timeout=None,
                 read_speed_limit=None, write_speed_limit=None,
                 path_timeout=None, path_io_factory=pathio.PathIO,
                 encoding="utf-8", ssl=None, parse_list_line_custom=None,
                 **siosocks_asyncio_kwargs):
        self.socket_timeout = socket_timeout
        self.throttle = StreamThrottle.from_limits(
            read_speed_limit,
            write_speed_limit,
        )
        self.path_timeout = path_timeout
        self.path_io = path_io_factory(timeout=path_timeout)
        self.encoding = encoding
        self.stream = None
        self.ssl = ssl
        self.parse_list_line_custom = parse_list_line_custom
        self._open_connection = partial(open_connection, ssl=self.ssl,
                                        **siosocks_asyncio_kwargs) 
开发者ID:aio-libs,项目名称:aioftp,代码行数:20,代码来源:client.py

示例15: run

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import open_connection [as 别名]
def run(self):
		try:
			self.in_queue = asyncio.Queue()
			self.out_queue = asyncio.Queue()
			self.reader, self.writer = await asyncio.wait_for(
				asyncio.open_connection(
					self.target.serverip if self.target.serverip is not None else self.target.host, 
					self.target.port, 
					ssl=self.target.get_ssl_context()
					),
				timeout = self.target.timeout
			)

			self.handle_in_task = asyncio.create_task(self.handle_in_q())
			self.handle_out_task = asyncio.create_task(self.handle_out_q())
			return True, None
		except Exception as e:
			return False, e 
开发者ID:skelsec,项目名称:msldap,代码行数:20,代码来源:tcp.py


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