3

I am building a TCP Client in Python, that is supposed to try to connect to the server until a connection is established or the program is closed. I define a timeout on a blocking socket, but after the first attempt to connect I receive

BlockingIOError: [Errno 114] Operation already in progress

Here is a little code example:

import socket

TCP_IP = '192.168.1.10'
TCP_PORT = 7


class TcpClient:
    def __init__(self):
        self.s = socket.socket(socket.AF_INET,  socket.SOCK_STREAM)
        self.s.settimeout(5)

    def connect(self):
        self.s.connect((TCP_IP,  TCP_PORT))


if __name__ == "__main__":
    client = TcpClient()
    while True:
        try:
            client.connect()
        except socket.timeout:
            pass

If I understand the python documentation correctly, the timeout should occur when the connection attempt was not successful. That would mean that the socket is not trying to establish a connection anymore, but it seems like it still is.

I tried to close the socket, too, but then I would need to create a new socket for every new connection attempt. I cannot believe that this is the perfect solution.

I am open for any suggestions or help regarding this problem. Thank you!

an1ge
  • 43
  • 2
  • 5
  • The socket is probably in TIMW_WAIT state after closing. To force it to be usable immediately use the setsockopt with SO_REUSEADDR – C. Gonzalez Oct 02 '17 at 21:02
  • I found another question on stackoverflow. The answer there is that sockets that are broken once should not be reused. I am creating a new socket object now every time the connection attempt failed. – an1ge Oct 03 '17 at 12:23
  • https://stackoverflow.com/questions/2237489/reusing-socket-descriptor-on-connection-failure – an1ge Oct 03 '17 at 13:35

0 Answers0