1

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
Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117
ROBERT RICHARDSON
  • 2,077
  • 4
  • 24
  • 57

1 Answers1

2

socketserver.BaseServer is a common base class for both UDP and TCP servers.

Your code will work if your server inherits instead from socketserver.TCPServer.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • Drat. I knew it would be something that would make me look like an idiot. Thanks very much! – ROBERT RICHARDSON Jan 07 '16 at 22:05
  • It doesn't make you look like an idiot. It makes you look like a programmer who is learning. I've been at it nearly fifty years and I'm still making mistakes, so don't feel too bad! – holdenweb Jan 07 '16 at 22:09