Python:SocketServer没有

2024-05-19 12:36:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用pythonsocketserver来等待消息,但要定期超时并执行其他一些处理。据我所知,下面的代码应该可以工作,但是对handle_request()的调用会抛出AttributeError异常,抱怨MyTCPServer对象没有属性“socket”。我做错什么了?在

import socketserver

class SingleTCPHandler(socketserver.BaseRequestHandler):
    # One instance per connection.  Override handle(self) to customize action.
    def handle(self):
        # self.request is the client connection
        data = self.request.recv(1024)  # clip input at 1Kb
        print ("Received data: " + data.decode())
        self.request.close()

class MyTCPServer(socketserver.BaseServer):

    def __init__(self, serverAddress, handler):
        super().__init__(serverAddress, handler)

    def handle_timeout(self):
        print ("No message received in {0} seconds".format(self.timeout))

if __name__ == "__main__":
    print ("SocketServerWithTimeout.py")
    tcpServer = MyTCPServer(("127.0.0.1", 5006), SingleTCPHandler)
    tcpServer.timeout = 5

    loopCount = 0
    while loopCount < 5:
        tcpServer.handle_request()
        print ("Back from handle_request")
        loopCount = loopCount + 1

Tags: selfdatainitrequestdeftimeoutconnectionclass
1条回答
网友
1楼 · 发布于 2024-05-19 12:36:45

socketserver.BaseServer是UDP和TCP服务器的通用基类。在

如果服务器从socketserver.TCPServer继承,则代码将正常工作。在

相关问题 更多 >