阻塞 - Python Socket Connect 设置超时无效
大家讲道理
大家讲道理 2017-04-18 10:14:04
0
2
833
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
黄舟

setdefaulttimeout is used to configure the socket instance

import socket
socket.setdefaulttimeout(0.01)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 也可以在这设置
# s.settimeout(0.01)
s.connect(("123123231", 12345))
刘奇
import socket
socket.setdefaulttimeout(0.01) 
socket.getaddrinfo("123123231", 12345)

This setdefaulttimeout is not useful for the socket module method, it just sets the timeout for the socket.socket object. This can be seen from the source code.

def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
                      source_address=None):
    host, port = address
    err = None
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
            if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
                sock.settimeout(timeout)
            if source_address:
                sock.bind(source_address)
            sock.connect(sa)
            return sock

        except error as _:
            err = _
            if sock is not None:
                sock.close()

    if err is not None:
        raise err
    else:
        raise error("getaddrinfo returns an empty list")
        
def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
    addrlist = []
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
        af, socktype, proto, canonname, sa = res
        addrlist.append((_intenum_converter(af, AddressFamily),
                         _intenum_converter(socktype, SocketKind),
                         proto, canonname, sa))
    return addrlist

Solution: (python3 code)

import socket
socket.setdefaulttimeout(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    sock.connect(("123123231", 12345))
except socket.timeout as e:
    print("timeout")
    pass
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template