I'm trying to add async functionality via the asyncio library, to a simple TCP server that I'm using. Here is my foobar example:
import os
import sys
import socket
class Server(object):
def __init__(self, addr):
self.ip, self.port = addr.split(":")
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def listen(self):
# Listen for incoming requests
self.socket.bind((self.ip, int(self.port)))
print("Listening")
while True:
try:
stream, addr = self.socket.accept()
self._handle_request(stream, addr)
except socket.timeout:
continue
def _handle_request(self, stream, addr):
# Here I'm handling the request (read and send response)
_mssg = self._recv_data(stream)
pass
def _recv_data(self, stream):
# unpacking the packed struct that was sent, reading
# 4-byte struct size first, then using stream.recv()
# until the entire message has been read
return 1
if __name__ == "__main__":
srv = Server("127.0.0.1:9999")
srv.listen()
I've read the Python docs example here regarding async, but I'm seeing that this example is using the built-in server functionality of the asyncio library. Could anyone help me generalize this to my simple TCP server? I need the flexibility of a custom solution (but still the functionality of the linked async server)