简体   繁体   English

如何修改socketserver中的handle方法

[英]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我正在学习socketserver模块,我正在按照示例进行操作,但我稍微修改了句柄 function


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现在,当我尝试使用 .netcat 并将某物发送到服务器时,我没有看到任何内容输出到控制台

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如何正确编辑 handle 方法,使其每次都打印客户端的地址

It is really important to understand the OOP concept and how to use it了解 OOP 的概念及其使用方法非常重要

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查看 socketserver 的源代码,我意识到我可以创建一个继承 BaseRequestHandler 的BaseRequestHandler而不是修改handler方法并将我的 class 传递给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()


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM