Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created May 7, 2019 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/583e9ebf461fe23d1718288a73aac484 to your computer and use it in GitHub Desktop.
Save Integralist/583e9ebf461fe23d1718288a73aac484 to your computer and use it in GitHub Desktop.
[Python3 Stream Server] #python3 #asyncio #stream #server
import asyncio
import contextvars
client_addr_var = contextvars.ContextVar('client_addr') # type:ignore
def render_goodbye():
# The address of the currently handled client can be accessed
# without passing it explicitly to this function.
client_addr = client_addr_var.get()
return f'Good bye, client @ {client_addr}\n'.encode()
# https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader
async def handle_request(reader, writer):
addr = writer.transport.get_extra_info('socket').getpeername()
client_addr_var.set(addr)
# In any code that we call is now possible to get
# client's address by calling 'client_addr_var.get()'.
while True:
line = await reader.readline()
print(line)
writer.write(render_goodbye())
writer.close()
if reader.at_eof():
print('BREAK')
break
async def main():
# https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.Server
srv = await asyncio.start_server(handle_request, '127.0.0.1', 8081)
async with srv:
await srv.serve_forever()
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment