Posted to tcl by metasyntax at Wed Mar 13 15:44:52 GMT 2013view raw
- #!/usr/bin/env tclsh
-
- # Set needed packages
- package require Thread
- package require http
-
- # Create the proc
- proc isHTTP {url} {
-
- # Set MasterID
- set mid [thread::id]
-
- # Create the thread
- set tid [thread::create {
-
- # Create thread proc
- proc isThreadHTTP {mid url} {
-
- # Set needed packages
- package require http
- package require tls
-
- # Add support for HTTPS
- ::http::register https 443 ::tls::socket
-
- # Set the token "10000/10s"
- if {[catch {set token [::http::geturl $url -binary 1 -timeout 10000]} error]} {
- set result "Error: Invalid URL"
- } else {
- upvar #0 $token state
-
- # Check if a timeout has occurred
- if {[::http::status $token]=="timeout"} {
- set result "Error: timeout occurred"
- # Check if statuscode was okay "http://en.wikipedia.org/wiki/List_of_HTTP_status_codes"
- } elseif {![regexp -nocase {^(20[0-7]|30[1-2]|405)$} [::http::ncode $token]]} {
- set result "Error: $ncode"
-
- # Check if whole file is downloaded
- } elseif {[::http::size $token]!=$state(totalsize) && [expr [string length $data]+1]!=[::http::size $token]} {
- set result "File error: [isWhatSize $state(totalsize)] <-remote local -> [isWhatSize [::http::size $token]]"
-
- # Check if the request was successful
- } elseif {[::http::status $token]=="ok"} {set data "[::http::data $token]"
-
- # Check if we got any error
- } elseif {[::http::status $token]=="error"} {set result "Error: [::http::error $token]"
-
- # Cleanup the memory we used
- } elseif {[info exists token]} {
- ::http::cleanup $token
- }
- }
-
- # Return result
- if {[info exists result]} {
- thread::send -async $mid [list set asdf [list 0 $result]]
- } else {
- thread::send -async $mid [list set asdf [list 1 $data]]
- }
- thread::release
- }
- thread::wait
- }]
- thread::send -async $tid "isThreadHTTP $mid $url"
- }
-
- # Set the url
- set url "http://www.google.se/images/google_favicon_128.png"
-
- isHTTP $url
-
- vwait asdf
- # Try to get the results
- puts "Data: [lindex $asdf 1]"
-
- # Try to show something else in mean time
- puts "It works"