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


Python usocket.getaddrinfo方法代码示例

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


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

示例1: start_server

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def start_server(client_coro, host, port, backlog=10):
    if DEBUG and __debug__:
        log.debug("start_server(%s, %s)", host, port)
    ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
    ai = ai[0]
    s = _socket.socket(ai[0], ai[1], ai[2])
    s.setblocking(False)

    s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
    s.bind(ai[-1])
    s.listen(backlog)
    while True:
        if DEBUG and __debug__:
            log.debug("start_server: Before accept")
        yield IORead(s)
        if DEBUG and __debug__:
            log.debug("start_server: After iowait")
        s2, client_addr = s.accept()
        s2.setblocking(False)
        if DEBUG and __debug__:
            log.debug("start_server: After accept: %s", s2)
        extra = {"peername": client_addr}
        yield client_coro(StreamReader(s2), StreamWriter(s2, extra)) 
开发者ID:lemariva,项目名称:uPyCam,代码行数:25,代码来源:__init__.py

示例2: main

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def main(use_stream=True):
    while True:
        d.measure()
        data = b"api_key="+ API_KEY + "&field1=" + str(d.temperature()) + "&field2=" + str(d.humidity())
      
        s = _socket.socket()
        ai = _socket.getaddrinfo(HOST, 443)
        addr = ai[0][-1]
        s.connect(addr)
    
        s = ssl.wrap_socket(s)
    
        
        s.write("POST /update HTTP/1.0\r\n")
        s.write("Host: " + HOST + "\r\n")
        s.write("Content-Length: " + str(len(data)) + "\r\n\r\n")
        s.write(data)
        print(s.read(128))
    
        s.close()
        time.sleep(60) 
开发者ID:bechynsky,项目名称:Micropython,代码行数:23,代码来源:thingspeak.py

示例3: socket_connect

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def socket_connect(self):
        if self.sock is not None:
            self.sock.close()
        try:
            self.sock = socket.socket()
            addr = socket.getaddrinfo(self.server, self.port)
            if addr == []:
                if self.addr_save:
                    try:
                        self.socket_connect(self.addr_save)
                        return
                    except:
                        raise OSError('addr get fail')
            addr = addr[0][-1]
            self.addr_save = addr
            self.sock.connect(addr)
            return True
        except OSError:
            return False 
开发者ID:m5stack,项目名称:UIFlow-Code,代码行数:21,代码来源:simple.py

示例4: open_connection

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def open_connection(host, port):
    try:
        import usocket as socket
    except ImportError:
        import socket
    ai = socket.getaddrinfo(host, port)[0] # TODO this is blocking!
    s = socket.socket()
    s.setblocking(False)
    ss = Stream(s)
    try:
        s.connect(ai[-1])
    except OSError as er:
        if er.args[0] != 115: # EINPROGRESS
            raise er
    yield _io_queue.queue_write(s)
    return ss, ss

# Class representing a TCP stream server, can be closed and used in "async with" 
开发者ID:peterhinch,项目名称:micropython-samples,代码行数:20,代码来源:__init__.py

示例5: run

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def run(timeout, nconns=10, verbose=False):
    addr = socket.getaddrinfo('0.0.0.0', PORT, 0, socket.SOCK_STREAM)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    socks.append(s)
    s.bind(addr)
    s.listen(nconns)
    verbose and print('Awaiting connection.')
    while True:
        yield asyncio.IORead(s)  # Register socket for polling
        conn, addr = s.accept()
        conn.setblocking(False)
        try:
            idstr = await readline(conn, timeout)
            verbose and print('Got connection from client', idstr)
            socks.append(conn)
            Connection.go(int(idstr), timeout, verbose, conn)
        except OSError:
            if conn is not None:
                conn.close()

# A Connection persists even if client dies (minimise object creation).
# If client dies Connection is closed: .close() flags this state by closing its
# socket and setting .conn to None (.ok() == False). 
开发者ID:peterhinch,项目名称:micropython-samples,代码行数:26,代码来源:server.py

示例6: __init__

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,
                 ssl=False, ssl_params={}):
        if port == 0:
            port = 8883 if ssl else 1883
        self.client_id = client_id
        self.sock = None
        self.addr = socket.getaddrinfo(server, port)[0][-1]
        self.ssl = ssl
        self.ssl_params = ssl_params
        self.pid = 0
        self.cb = None
        self.user = user
        self.pswd = password
        self.keepalive = keepalive
        self.lw_topic = None
        self.lw_msg = None
        self.lw_qos = 0
        self.lw_retain = False 
开发者ID:ayoy,项目名称:upython-aq-monitor,代码行数:20,代码来源:mqtt.py

示例7: run

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def run(self, host='0.0.0.0', port=5000, debug=False):
        self.debug = debug

        s = socket.socket()
        ai = socket.getaddrinfo(host, port)
        addr = ai[0][-1]

        if self.debug:  # pragma: no cover
            print('Starting {mode} server on {host}:{port}...'.format(
                mode=concurrency_mode, host=host, port=port))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(addr)
        s.listen(5)

        while True:
            sock, addr = s.accept()
            create_thread(self.dispatch_request, sock, addr) 
开发者ID:miguelgrinberg,项目名称:microdot,代码行数:19,代码来源:microdot.py

示例8: __init__

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def __init__(self, server, port):
        # On ESP32 need to submit WiFi credentials
        self._sta_if = network.WLAN(network.STA_IF)
        self._sta_if.active(True)
        # Note that the following blocks, potentially for seconds, owing to DNS lookup
        self._addr = socket.getaddrinfo(server, port)[0][-1]
        self._sock = socket.socket()
        self._sock.setblocking(False)
        try:
            self._sock.connect(addr)
        except OSError as e:
            if e.args[0] not in BUSY_ERRORS:
                raise
        if ESP32:  # Revolting kludge :-(
            loop = asyncio.get_event_loop()
            loop.create_task(self._idle_task()) 
开发者ID:peterhinch,项目名称:micropython-async,代码行数:18,代码来源:sock_nonblock.py

示例9: run

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def run(self, loop, port=8123):
        addr = socket.getaddrinfo('0.0.0.0', port, 0, socket.SOCK_STREAM)[0][-1]
        s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # server socket
        s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s_sock.bind(addr)
        s_sock.listen(5)
        self.socks = [s_sock]  # List of current sockets for .close()
        print('Awaiting connection on port', port)
        poller = select.poll()
        poller.register(s_sock, select.POLLIN)
        client_id = 1  # For user feedback
        while True:
            res = poller.poll(1)  # 1ms block
            if res:  # Only s_sock is polled
                c_sock, _ = s_sock.accept()  # get client socket
                loop.create_task(self.run_client(c_sock, client_id))
                client_id += 1
            await asyncio.sleep_ms(200) 
开发者ID:peterhinch,项目名称:micropython-async,代码行数:20,代码来源:userver.py

示例10: open_connection

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def open_connection(host, port, ssl=False):
    if DEBUG and __debug__:
        log.debug("open_connection(%s, %s)", host, port)
    ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
    ai = ai[0]
    s = _socket.socket(ai[0], ai[1], ai[2])
    s.setblocking(False)
    try:
        s.connect(ai[-1])
    except OSError as e:
        if e.args[0] != uerrno.EINPROGRESS:
            raise
    if DEBUG and __debug__:
        log.debug("open_connection: After connect")
    yield IOWrite(s)
#    if __debug__:
#        assert s2.fileno() == s.fileno()
    if DEBUG and __debug__:
        log.debug("open_connection: After iowait: %s", s)
    if ssl:
        print("Warning: uasyncio SSL support is alpha")
        import ussl
        s.setblocking(True)
        s2 = ussl.wrap_socket(s)
        s.setblocking(False)
        return StreamReader(s, s2), StreamWriter(s2, {})
    return StreamReader(s), StreamWriter(s, {}) 
开发者ID:lemariva,项目名称:uPyCam,代码行数:29,代码来源:__init__.py

示例11: connect

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def connect(self):
        if not self._has_connected:
            await self.wifi_connect()  # On 1st call, caller handles error
            # Note this blocks if DNS lookup occurs. Do it once to prevent
            # blocking during later internet outage:
            self._addr = socket.getaddrinfo(self.server, self.port)[0][-1]
        self._in_connect = True  # Disable low level ._isconnected check
        clean = self._clean if self._has_connected else self._clean_init
        try:
            await self._connect(clean)
        except Exception:
            self.close()
            raise
        self.rcv_pids.clear()
        # If we get here without error broker/LAN must be up.
        self._isconnected = True
        self._in_connect = False  # Low level code can now check connectivity.
        loop = asyncio.get_event_loop()
        loop.create_task(self._wifi_handler(True))  # User handler.
        if not self._has_connected:
            self._has_connected = True  # Use normal clean flag on reconnect.
            loop.create_task(
                self._keep_connected())  # Runs forever unless user issues .disconnect()

        loop.create_task(self._handle_msg())  # Tasks quit on connection fail.
        loop.create_task(self._keep_alive())
        if self.DEBUG:
            loop.create_task(self._memory())
        loop.create_task(self._connect_handler(self))  # User handler.

    # Launched by .connect(). Runs until connectivity fails. Checks for and
    # handles incoming messages. 
开发者ID:peterhinch,项目名称:micropython-mqtt,代码行数:34,代码来源:mqtt_as.py

示例12: get_time

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def get_time(self):
        if not self.isconnected():
            return 0
        res = await self.wan_ok()
        if not res:
            return 0  # No internet connectivity.
        # connectivity check is not ideal. Could fail now... FIXME
        # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 3155673600
        host = "pool.ntp.org"
        NTP_QUERY = bytearray(48)
        NTP_QUERY[0] = 0x1b
        t = 0
        async with self.lock:
            addr = socket.getaddrinfo(host, 123)[0][-1]  # Blocks 15s if no internet
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.setblocking(False)
            try:
                s.connect(addr)
                await self._as_write(NTP_QUERY, 48, s)
                await asyncio.sleep(2)
                msg = await self._as_read(48, s)
                val = struct.unpack("!I", msg[40:44])[0]
                t = val - NTP_DELTA
            except OSError:
                pass
            s.close()

        if t < 16 * 365 * 24 * 3600:
            t = 0
        self.dprint('Time received: ', t)
        return t 
开发者ID:peterhinch,项目名称:micropython-mqtt,代码行数:34,代码来源:mqtt.py

示例13: main

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def main():
    led = machine.Pin(2, machine.Pin.OUT)
    led.value(1)
    s = socket.socket()
    ai = socket.getaddrinfo("0.0.0.0", 8080)
    addr = ai[0][-1]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to http://<this_host>:8080/")

    counter = 0
    while True:
        res = s.accept()
        client_s = res[0]
        client_addr = res[1]
        req = client_s.recv(1024)
        cmd = getCommand(req)
        
        print(cmd)

        if (cmd == "/on"):
            led.value(0)
        elif (cmd == "/off"):
            led.value(1)
        
        client_s.send(CONTENT % counter)
        client_s.close()
        counter += 1
        print() 
开发者ID:bechynsky,项目名称:Micropython,代码行数:34,代码来源:server_led_control.py

示例14: _tcp_server

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def _tcp_server(self, host, port, backlog):
        """TCP Server implementation.
        Opens socket for accepting connection and
        creates task for every new accepted connection
        """
        addr = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0][-1]
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(False)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(addr)
        sock.listen(backlog)
        try:
            while True:
                yield asyncio.IORead(sock)
                csock, caddr = sock.accept()
                csock.setblocking(False)
                # Start handler / keep it in the map - to be able to
                # shutdown gracefully - by close all connections
                self.processed_connections += 1
                hid = id(csock)
                handler = self._handler(asyncio.StreamReader(csock),
                                        asyncio.StreamWriter(csock, {}))
                self.conns[hid] = handler
                self.loop.create_task(handler)
                # In case of max concurrency reached - temporary pause server:
                # 1. backlog must be greater than max_concurrency, otherwise
                #    client will got "Connection Reset"
                # 2. Server task will be resumed whenever one active connection finished
                if len(self.conns) == self.max_concurrency:
                    # Pause
                    yield False
        except asyncio.CancelledError:
            return
        finally:
            sock.close() 
开发者ID:belyalov,项目名称:tinyweb,代码行数:37,代码来源:server.py

示例15: time

# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import getaddrinfo [as 别名]
def time(host = 'pool.ntp.org', port=123):
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1b
    NTP_DELTA = 2208988800 # 1970-01-01 00:00:00
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1)
    res = s.sendto(NTP_QUERY, addr)
    msg = s.recv(48)
    s.close()
    val = struct.unpack("!I", msg[40:44])[0]
    return val - NTP_DELTA 
开发者ID:artem-smotrakov,项目名称:esp32-weather-google-sheets,代码行数:14,代码来源:ntp.py


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