anecdata / Socket

TCP and UDP socket examples and helpers for use with CircuitPython.
MIT License
26 stars 4 forks source link

kindly add tcp connection example with asyncio #2

Open rastinder opened 1 year ago

rastinder commented 1 year ago
TIMEOUT = None
BACKLOG = 1
MAXBUF = 1
buf = bytearray(MAXBUF)
s = pool.socket(pool.AF_INET, pool.SOCK_STREAM)
#s.settimeout(TIMEOUT)
#s.setblocking(False)

s.bind((HOST, PORT))
s.listen(BACKLOG)

while True:
    try:
        print("Waiting for connection...")
        conn, addr = s.accept()
        conn.settimeout(TIMEOUT)
        print("Accepted from", addr)

        try:
            response = requests.post(sendURL + "?chat_id=" + str(chatId) + "&text= pico w with address " + HOST  + " is connected to " + str(addr))
        except:
            print('telegram msg problem')

        while True:  # Loop to handle commands within the connection
            try:
                name = ''
                name1 = ''
                while True:
                    print('Ready to receive again')
                    name1 = conn.recv_into(buf)
                    print("Received")
                    if name1:
                        data = buf[:name1].decode("utf-8")
                        if data != "|":
                            name += data
                        else:
                            name1 = ''
                            try:
                                hid_work(name)
                            except Exception as e:
                                try:
                                    requests.post(sendURL + "?chat_id=" + str(chatId) + "&text=" + str(wifi.radio.ipv4_address) + str(traceback.format_exception(e)) + " hid_work encountered a problem")
                                except:
                                    print('telegram msg problem')
                            name = ''
            except:
                break  # Connection dropped, break inner loop

    except:
        pass  # Accepting connection failed, continue to try again`

if connection drop then i think code remains stuck on name1 = conn.recv_into(buf) but i want it to be unstuck only if connection drops

anecdata commented 1 year ago

I hope you don't mind, I edited to add syntax highlighting.

anecdata commented 1 year ago

You may have moved way past this by now, but... I don't think you necessarily need async for this, just a timeout so that it's non-blocking. Note that you can have different timeouts for the listening socket (s), and for the connection socket (conn), and you can change the timeouts at any time within the code if desired. Adding timeouts probably also means wrapping more network calls in try / except.