This is a creation in Article, where the information may have evolved or changed.
server的实现type tcpKeepAliveListener struct { errerror) { err := ln.AcceptTCP() iferr != nil { return } tc.SetKeepAlive(true) tc.SetKeepAlivePeriod(3time.Minute) return tc, nil}这里可以看出:tc.SetKeepAlivePeriod(3time.Minute) 设置了超时时间为3分钟,这个先到这里下面会用到
Func main () {HTTP. Handlefunc("/", route) HTTP. Listenandserve(": 1789", nil)}func Route (W http. Responsewriter, R *http. Request) {Log. Printf("addr->%s\turi->%s\n"R. RemoteaddrR. URL. Path) Defer R. Body. Close() Switch R. URL. Path{case"/": W. Write([]byte ("Welcome to Work-stacks")) case"/gettcp": Gettcp (W, R) default:http. NotFound(W, R)}} Func gettcp (w http. Responsewriter, R *http. Request) {//the *BUFIO returned here. ReadwriterNo processing, production environment Note to the situation Bufferd Conn, _, Err: = W. (http. Hijacker). Hijack() if err! = Nil {log. Printf("Get hijacks failed:%s\n"Err. Error()) return} if Tcp,ok: = conn. (*net. Tcpconn); OK {Tcp. Setkeepaliveperiod( -* Time. Minute)}//Then you can do what you want to do. Conn. Close()}
Func Main () {req,Err: = http. Newrequest ("GET","Http://127.0.0.1:1789/gettcp", nil)if Err! = Nil {Log. Println ("Create request failed:%s\n",Err.Error()) Return} conn, _: = Net. Dial ("TCP","127.0.0.1:1789") Defer Conn. Close () Hclient: = Httputil. NEWCLIENTCONN (conn, nil)Err= Hclient. Write (req)if Err! = Nil {Log. Printf ("Send request failed:%s\n",Err) return}}