Socket icon indicating copy to clipboard operation
Socket copied to clipboard

kindly add tcp connection example with asyncio

Open rastinder opened this issue 1 year ago • 2 comments

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

rastinder avatar Aug 18 '23 18:08 rastinder