Search code examples
python-3.xsocketstimeoutrecv

Can't set timeout for python 3 recv


I am trying to get a time out on the code below. But it just hangs at the recv and never times out. Can someone point to what I am doing wrong? I have looked and I can't seem to find too much on it.

import socket

host = "localhost"
port = 8888

# create socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# give object the ip and port to listen on
server_address = (host, port)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)
# how many listeners
sock.listen(0)
# sets the time out
sock.settimeout(10)

while True:
    print('waiting for a connection')
    try:
        #this waits for a connection from the sending side.
        connection, client_address = sock.accept()
        print('connection from', client_address)

        start = False
        message = ""
        while client_address != "":
            #this listens and waits for data to be sent and sets it to the data variable
            data = connection.recv(32000).decode()

Solution

  • You have set an accept timeout on the listening socket, not a read timeout on the receiving socket.