Skip to content

Instantly share code, notes, and snippets.

@deepanshululla
Last active January 2, 2023 16:58
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 deepanshululla/4530cab3e80f67ef46b1c669231c3001 to your computer and use it in GitHub Desktop.
Save deepanshululla/4530cab3e80f67ef46b1c669231c3001 to your computer and use it in GitHub Desktop.
import asyncio
class AsyncIOServer:
def __init__(self, host_name="localhost", port_num=6379, reuse_port=True):
self.host_name = host_name
self.port_num = port_num
self.reuse_port = reuse_port
async def __start_server(self):
self.server = await asyncio.start_server(self.__handle_connection,
self.host_name,
self.port_num,
reuse_port=True)
async with self.server:
await self.server.serve_forever()
print(f"Listening on {self.host_name}:{self.port_num}")
async def __handle_connection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
addr = writer.get_extra_info('peername')
print(f"Connected to {addr}")
while True:
try:
request = await reader.read(1024)
# request_msg = request.decode().strip()
response = "+PONG\r\n"
writer.write(response.encode())
await writer.drain()
except Exception as e:
print(f"Disconnected from {addr}")
break
async def listen_for_connections(self):
await self.__start_server()
if __name__ == "__main__":
s = AsyncIOServer()
asyncio.run(s.listen_for_connections())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment