Golang1.7 http and TCP use the same port for service

Source: Internet
Author: User
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}}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.