How to set a timeout for the Python recv() method?

Asked

Viewed 106 times

0

I’m creating a program in Python using socket, and I came across a bug in the program that occurs because the recv does not inform if the connection has been terminated or not. Someone there can tell me how to define a timeout for the method recv using the library itself socket and give me an example ?

I know there’s a method settimeout, however it did not make any difference in the program. I use windows in case someone needs to know my OS.

Part of my code:

self.__running = True
self.__stop = False
self.__socket.settimeout(10)

if self.__mode == self.CLIENT:

    # Essa variável irá guardar a quantidade de bytes recebidos
    received = 0

    # Cria um arquivo e um bufferWriter para salvar os dados do arquivo baixado
    file = io.FileIO(normpath(self.__path+"/"+self.__filename),'wb')
    bufferedWriter = io.BufferedWriter(file,self.__size)

    # Envia uma confirmação de que está pronto para receber os dados
    self.__socket.send(self.__OK.encode())

    while not self.__stop:

        data = self.__socket.recv(1024)
  • Try if not data: break after the line ...recv(1024), see if that’s what you want

  • Oh thank you, it was more or less just what I wanted. I did not know that the recv method launched an error, thank you.

1 answer

0


To solve the problem, I just needed to put the recv within a block try and if any errors were made, I would only use the break to leave the block. That way:

while not self.__stop:
    try:
        data = self.__socket.recv(1024)
    except:
        break

The problem is I didn’t know that the recv threw an error, and in addition to throwing an error it returns the value 0. Hence the Miguel said to use a check if not data:. Thank you Miguel!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.