Created
September 26, 2012 06:03
-
-
Save border/3786357 to your computer and use it in GitHub Desktop.
Http Hijack longpolling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"net" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"time" | |
) | |
var ( | |
u = flag.String("url", "http://127.0.0.1:8080/hijack", "Connection URL") | |
) | |
func Connect(nurl *url.URL) { | |
req := http.Request{ | |
Method: "GET", | |
Header: http.Header{}, | |
URL: nurl, | |
} | |
dial, err := net.Dial("tcp", nurl.Host) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
clientconn := httputil.NewClientConn(dial, nil) | |
clientconn.Do(&req) | |
defer clientconn.Close() | |
rwc, br := clientconn.Hijack() | |
defer rwc.Close() | |
for { | |
buf := make([]byte, 100) | |
s, err := br.Read(buf) | |
if err != nil { | |
fmt.Println("Read Err: " + err.Error()) | |
} | |
fmt.Printf("size: %d, buf: %s\n", s, string(buf)) | |
time.Sleep(1 * time.Second) | |
buf = nil | |
} | |
time.Sleep(5 * time.Second) | |
} | |
func main() { | |
flag.Parse() | |
nurl, _ := url.Parse(*u) | |
Connect(nurl) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/http" | |
"strconv" | |
"time" | |
) | |
func main() { | |
http.HandleFunc("/", hello) | |
http.HandleFunc("/hijack", hijack) | |
log.Println("Linsten on: 8080") | |
http.ListenAndServe(":8080", nil) | |
} | |
func hijack(w http.ResponseWriter, r *http.Request) { | |
hj, ok := w.(http.Hijacker) | |
if !ok { | |
http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError) | |
return | |
} | |
rwc, bufrw, err := hj.Hijack() | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
defer rwc.Close() | |
if bufrw != nil { | |
bufrw.Flush() | |
} | |
bufrw.WriteRune('\n') // 为什么必须要这句,如果没有client收不到数据 | |
count := 0 | |
for { | |
count++ | |
bufrw.WriteString(strconv.Itoa(count)) | |
bufrw.WriteString(", Now we're speaking raw TCP. Say hi: ") | |
bufrw.WriteString(time.Now().String()) | |
bufrw.Flush() | |
time.Sleep(1 * time.Second) | |
} | |
time.Sleep(10 * time.Second) | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("hello, world\n")) | |
w.Write([]byte(time.Now().String())) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment