'How to modify handle method in socketserver

I am learning the socketserver module and I am following the example but I modified the handle function a bit


class CustomServer(socketserver.BaseRequestHandler):


    def handle(self):

        self.data = self.request.recv(1024).strip()
        print(f">{self.client_address[0]}: {self.data}")

    def send(self, targets=[]):
        if not targets:
            return 



if __name__ == "__main__":
    HOST, PORT = "localhost", 6666
    with socketserver.TCPServer((HOST, PORT), CustomServer) as server:
        server.serve_forever()

Now when I try to use netcat and send sth to the server I don't see anything being outputted to the console

nc -v 10.0.0.112 6666

How do you properly edit the handle method so that it will print the address of the client each time



Solution 1:[1]

It is really important to understand the OOP concept and how to use it

Looking at the source code for socketserver I realized that I can create a class that inherits the BaseRequestHandler than I modified the handler method and passed my class to the TCPServer


class CustomHandler(BaseRequestHandler):

    def handle(self):
        self.data = self.request.recv(1024).strip()
        print(f">{self.client_address[0]}: {self.data}")






if __name__ == "__main__":
    HOST, PORT = "0.0.0.0", 6666
    server = TCPServer(((HOST, PORT)), CustomHandler)

    server.serve_forever()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 epic_rain