req icon indicating copy to clipboard operation
req copied to clipboard

通过transport.SetDial自定义dial来做到指定tcp连接使用指定ip后无法关闭连接。

Open wuchuwei opened this issue 4 months ago • 0 comments

代码如下 ` dia := func(ctx context.Context, network, addr string) (net.Conn, error) { // Specify the custom IP address you want to connect to dialer := &net.Dialer{ Timeout: 800 * time.Millisecond, // Set connection timeout KeepAlive: -1, // You can specify the local interface by setting LocalAddr here if needed } // Resolve and use the specified IP address (114.114.114.114 for this example) ipAddr := ip+":443" return dialer.DialContext(ctx, network, ipAddr) }

// Create a req client with the custom transport.
client := req.C().SetTimeout(2000 * time.Millisecond).DisableKeepAlives().SetRedirectPolicy(req.NoRedirectPolicy()).SetTLSFingerprintChrome().SetUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
transport := client.GetTransport()
transport.MaxIdleConnsPerHost = -1
transport.DisableKeepAlives = true
    transport.SetDial(dia)

// Make the request
resp, err := client.R().EnableCloseConnection().Get(url)
     io.Copy(ioutil.Discard, resp.Body)
   resp.Body.Close()
   transport.CloseIdleConnections()

` 无论如何做都无法主动关闭tcp连接。 我这个功能主要是对网站进行dns优选。找出那个ip相应快。功能是做出来了。但代码长时间运行就会出现大量未关闭的连接。 要如何才能主动关闭连接?

wuchuwei avatar Oct 16 '24 06:10 wuchuwei