Search code examples
pythonsocketsservertimeout

Python 2.7 server.socket timeout question


I have some python code that sometimes will block when a connection is opened up but no data is sent. I understand why it is waiting for 64 bits or less of data. It will wait forever. Is there a simple way to time out the connection if no data is received. Any help or suggestions would be greatly appreciated.

    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.bind(('', port))
    serversocket.listen(5) # become a server socket, maximum 5 connections
    while 1:
        try:
            while 1:
               # print "Waiting for oonnection..."
                connection, address = serversocket.accept()
                buf = connection.recv(64)

Solution

  • You can use socket.settimeout(value) where value is number of seconds.

        serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serversocket.bind(('', port))
        serversocket.listen(5) # become a server socket, maximum 5 connections
    
        while 1:
            try:
                while 1:
                   # print "Waiting for oonnection..."
                    connection, address = serversocket.accept()
                    connection.settimeout(5) # Set 5 seconds timeout to receive 64 bytes of data
    
                    buf = connection.recv(64)
    
            except socket.timeout:
                print("Timeout happened -- goting back to accept another connection")