kindly add tcp connection example with asyncio
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
I hope you don't mind, I edited to add syntax highlighting.
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.
There is now an asyncio TCP server example:
https://github.com/anecdata/Socket/blob/main/examples/tcp_server_CircuitPython_NATIVE_async.py
I think this is answered. Closing. Feel free to re-open or open a new issue if questions remain.