Python socket connection timeout

后端 未结 3 1952
忘了有多久
忘了有多久 2020-11-30 00:45

I have a socket that I want to timeout when connecting so that I can cancel the whole operation if it can\'t connect yet it also want to use the makefile for the socket whic

3条回答
  •  爱一瞬间的悲伤
    2020-11-30 01:48

    You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(10)
    sock.connect(address)
    sock.settimeout(None)
    fileobj = sock.makefile('rb', 0)
    

提交回复
热议问题