I want to use a Python socketserver to wait for a message, but to time out periodically and do some other processing. As far as I can tell, the following code should work, but the call to handle_request() throws an AttributeError exception, complaining that MyTCPServer object has no attribute 'socket'. What am I doing wrong?
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