Skip to content

Instantly share code, notes, and snippets.

@arseniyturin
Created December 9, 2021 19:56
Show Gist options
  • Save arseniyturin/98f1eef5887f1e3ed106032766114ab6 to your computer and use it in GitHub Desktop.
Save arseniyturin/98f1eef5887f1e3ed106032766114ab6 to your computer and use it in GitHub Desktop.
Example of the asynchronous socket server with asyncio
# David Beazley async socket server example
# Loops very similar to a 'regular' threaded socket server
# Except we create an event loop and use async/await syntax
import asyncio
import socket
loop = asyncio.get_event_loop()
async def server(address):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(address)
sock.listen(5)
sock.setblocking(False)
while True:
client, addr = await loop.sock_accept(sock)
print('Connection from: ', addr)
loop.create_task(echo_handler(client))
async def echo_handler(client):
with client:
while True:
data = await loop.sock_recv(client, 10000)
if not data:
break
await loop.sock_sendall(client, data)
print('Connection closed')
loop.create_task(server(('', 8000)))
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment