Python usocket.SOL_SOCKET Examples

The following are 15 code examples of usocket.SOL_SOCKET(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module usocket , or try the search function .
Example #1
Source File: __init__.py    From uPyCam with Apache License 2.0 6 votes vote down vote up
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)) 
Example #2
Source File: server.py    From micropython-samples with MIT License 6 votes vote down vote up
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). 
Example #3
Source File: __init__.py    From micropython-samples with MIT License 6 votes vote down vote up
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)) 
Example #4
Source File: __init__.py    From microdot with MIT License 6 votes vote down vote up
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)) 
Example #5
Source File: microdot.py    From microdot with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: __init__.py    From pysmartnode with MIT License 6 votes vote down vote up
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)) 
Example #7
Source File: userver.py    From micropython-async with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: __init__.py    From microhomie with MIT License 6 votes vote down vote up
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)) 
Example #9
Source File: server_led_control.py    From Micropython with MIT License 5 votes vote down vote up
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() 
Example #10
Source File: server.py    From tinyweb with MIT License 5 votes vote down vote up
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() 
Example #11
Source File: main.py    From uPyEcho with Apache License 2.0 5 votes vote down vote up
def init_socket(self):
        ok = True
        self.ip = "239.255.255.250"
        self.port = 1900
        try:
            # This is needed to join a multicast group
            self.mreq = struct.pack("4sl", inet_aton(self.ip), INADDR_ANY)
            # Set up server socket
            self.ssock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                self.ssock.bind(("", self.port))
            except Exception as e:
                dbg("WARNING: Failed to bind %s:%d: %s", (self.ip, self.port, e))
                ok = False
            try:
                dbg(
                    "IP: "
                    + str(socket.IPPROTO_IP)
                    + " IP_ADD_MEMBERSHIP: "
                    + str(socket.IP_ADD_MEMBERSHIP)
                    + " mreq: "
                    + str(self.mreq)
                )
                self.ssock.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq
                )
            except Exception as e:
                dbg("WARNING: Failed to join multicast group!: " + str(e))
                ok = False

        except Exception as e:
            dbg("Failed to initialize UPnP sockets!")
            return False
        if ok:
            dbg("Listening for UPnP broadcasts") 
Example #12
Source File: server.py    From micropython-iot with MIT License 5 votes vote down vote up
def run(expected, verbose=False, port=8123, timeout=2000):
    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(len(expected) + 2)
    verbose and print('Awaiting connection.', port)
    poller = select.poll()
    poller.register(s_sock, select.POLLIN)
    to_secs = timeout / 1000  # ms -> secs
    while True:
        res = poller.poll(1)  # 1ms block
        if res:  # Only s_sock is polled
            c_sock, _ = s_sock.accept()  # get client socket
            c_sock.setblocking(False)
            try:
                data = await _readid(c_sock, to_secs)
            except OSError:
                c_sock.close()
            else:
                Connection.go(to_secs, data, verbose, c_sock, s_sock,
                              expected)
        await asyncio.sleep(0.2)


# 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 .sock to None (.status() == False). 
Example #13
Source File: __init__.py    From micropython-samples with MIT License 5 votes vote down vote up
def _serve(self, cb, host, port, backlog):
        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)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(ai[-1])
        s.listen(backlog)
        self.task = cur_task
        # Accept incoming connections
        while True:
            try:
                yield _io_queue.queue_read(s)
            except CancelledError:
                # Shutdown server
                s.close()
                return
            s2, addr = s.accept()
            s2.setblocking(False)
            s2s = Stream(s2, {'peername': addr})
            create_task(cb(s2s, s2s))

# Helper function to start a TCP stream server, running as a new task
# TODO could use an accept-callback on socket read activity instead of creating a task 
Example #14
Source File: server.py    From esp32-weather-google-sheets with MIT License 4 votes vote down vote up
def start(self):
        s = socket.socket()

        ai = socket.getaddrinfo(self.ip, self.port)
        addr = ai[0][-1]

        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(addr)
        s.listen(5)
        print('server started on %s:%s' % addr)

        # main server loop
        while True:
            print('waiting for connection ...')
            res = s.accept()
            client_s = res[0]
            print('accepted')

            try:
                # read the status line
                status_line = client_s.readline().decode('utf-8').strip()

                # content length
                length = 0

                # read all headers, and look for Content-Length header
                # in order to read data from the request
                headers = {}
                while True:
                    h = client_s.readline()
                    if h == b"" or h == b"\r\n":
                        break
                    parts = h.decode('utf-8').strip().lower().split(':')
                    name = parts[0].strip()
                    value = parts[1].strip()
                    headers[name] = value
                    if name == 'content-length':
                        length = int(value)

                # read data from the request
                data = client_s.read(length).decode('utf-8')

                # let the handler to process the request
                self.handler.handle(client_s, status_line, headers, data)

                client_s.close()
            except Exception as e:
                print(e)
                raise e 
Example #15
Source File: __init__.py    From micropython-async with MIT License 4 votes vote down vote up
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)
    try:
        while True:
            try:
                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}
                # Detach the client_coro: put it on runq
                yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
                s2 = None

            except Exception as e:
                if len(e.args)==0:
                    # This happens but shouldn't. Firmware bug?
                    # Handle exception as an unexpected unknown error:
                    # collect details here then close try to continue running
                    print('start_server:Unknown error: continuing')
                    sys.print_exception(e)
                if not uerrno.errorcode.get(e.args[0], False):
                    # Handle exception as internal error: close and terminate
                    # handler (user must trap or crash)
                    print('start_server:Unexpected error: terminating')
                    raise
    finally:
        if s2:
            s2.close()
        s.close()