Last active
January 2, 2023 16:56
-
-
Save deepanshululla/9e8dc68d152ec387ab7021f9458301bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import socket | |
from asyncio import AbstractEventLoop | |
class AsyncSocketServer: | |
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 | |
self.__init_server() | |
def __init_server(self): | |
self.socket = socket.create_server((self.host_name, self.port_num), reuse_port=self.reuse_port) | |
self.socket.setblocking(False) | |
print(f"Listening on {(self.host_name, self.port_num)}") | |
async def __reply_to_ping(self, conn, addr, loop: AbstractEventLoop): | |
try: | |
data = b'+PONG\r\n' | |
while await loop.sock_recv(conn, 1024): | |
await loop.sock_sendall(conn, data) | |
except ConnectionError: | |
print(f"Disconnected from {addr}") | |
async def listen_for_connections(self): | |
while True: | |
loop = asyncio.get_event_loop() | |
conn, addr = await loop.sock_accept(self.socket) | |
# conn.setblocking(False) | |
print(f"Connected to {addr}") | |
asyncio.create_task(self.__reply_to_ping(conn, addr, loop)) | |
def __del__(self): | |
self.socket.close() | |
if __name__ == "__main__": | |
s = AsyncSocketServer() | |
asyncio.run(s.listen_for_connections()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment