4 ms·
Use asyncio. Bind to a socket, set blocking False, then asyncio.run(on_new_connection(sock)). Inside that coroutine get the loop and await loop.sock_accept(soc
by Siecje 3y ago
Use asyncio. Bind to a socket, set blocking False, then asyncio.run(on_new_connection(sock)).
Inside that coroutine get the loop and await loop.sock_accept(sock)
And then asyncio.create_task(on_connection_data(connection)).
The only gotcha is you need to keep a reference to that task so it doesn't get garbage collected.
- staticautomatic 3y agoGet garbage collected by what? Doesn’t Python use reference counting?
- d0mine 3y agoasyncio doesn't store strong references to tasks. It is your responsibility to keep the ref: https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task https://docs.python.org/3/library/asyncio-task.html#asyncio.... Consider organizing the code using TaskGroup.
- jph00 3y agoPython has a GC.
- foresto 3y agoThe reference implementation (CPython) does use reference counting, but that is not its only approach to garbage collection. "The default build implementation is a generational collector. The free-threaded build is non-generational; each collection scans the entire heap." https://devguide.python.org/internals/garbage-collector/ https://devguide.python.org/internals/garbage-collector/ https://docs.python.org/3/library/gc.html https://docs.python.org/3/library/gc.html (And as someone else pointed out, asyncio's event loop keeps only weak references to tasks, so the GC implementation doesn't really matter here.)
- bmitc 3y agoThank you. Do you have more information regarding this? Why do I await the socket acceptance? How do I handle the disconnect? How do I send messages into and out of the coroutine?