首页 > 解决方案 > 对 HTTP 请求重用 TCP 套接字

问题描述

我试图让 Tcl http 包重用与服务器的初始 TCP 连接以遵循重定向响应。从手册页中,我得到的印象是指定选项-keepalive 1应该可以实现这一点。但是,在我的测试中,我观察到使用了两个单独的 TCP 连接。这是我的代码:

package require http

# Redirect test page
set url http://jigsaw.w3.org/HTTP/300/301.html

# Make the HTTP library report what it is doing
proc http::Log {args} {
    puts [join $args]
}

set tok [http::geturl $url -keepalive 1]
if {[http::ncode $tok] in {301 302}} {
    # Determine the new URL
    set meta [http::meta $tok]
    set key [lsearch -exact -nocase -inline [dict keys $meta] location]
    set loc [dict get $meta $key]
    http::cleanup $tok
    puts "Redirecting to: $loc"
    set tok [http::geturl $loc -keepalive 1]
}
puts [http::code $tok]
http::cleanup $tok

这会产生以下输出,清楚地表明每个请求都打开和关闭了一个套接字:

^A1 URL http://jigsaw.w3.org/HTTP/300/301.html - token ::http::1
Using sock560e29012cc0 for jigsaw.w3.org:80 - token ::http::1 keepalive
^B1 begin sending request - token ::http::1
^C1 end sending request - token ::http::1
^D1 begin receiving response - token ::http::1
^E1 end of response headers - token ::http::1
^F1 end of response body (unchunked) - token ::http::1
Closing connection jigsaw.w3.org:80 (sock sock560e29012cc0)
Redirecting to: http://jigsaw.w3.org/HTTP/300/Overview.html
^A2 URL http://jigsaw.w3.org/HTTP/300/Overview.html - token ::http::2
Using sock560e28f6e820 for jigsaw.w3.org:80 - token ::http::2 keepalive
^B2 begin sending request - token ::http::2
^C2 end sending request - token ::http::2
^D2 begin receiving response - token ::http::2
^E2 end of response headers - token ::http::2
^F2 end of response body (unchunked) - token ::http::2
Closing connection jigsaw.w3.org:80 (sock sock560e28f6e820)
HTTP/1.1 200 OK

我还需要做什么才能使用同一个 TCP 连接发送多个请求?

标签: tcl

解决方案


推荐阅读