go tcp通訊

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

go 的tcp的應用程式層代碼看起來極為簡單

1,多個協程同時Accept , 不知道這種實現有沒有什麼問題

2,多個協程同時處理網路IO事件, 貌似意味著, 有多少個串連過來就需要有多少個協程了, 對於go來說,一個進程支援足夠都的協程, 遠遠大於頻寬的限制

 

服務端代碼

ackage mainimport (       "net"       "time"       "fmt")func ca(){       a := recover()       fmt.Println("Catch", a)}func main(){       defer ca()       fmt.Println("main start")       L, e:=net.Listen("tcp", "127.0.0.1:7878")       if e != nil{              fmt.Println("this is null")              panic("claa null")       }       for index:=0; index<10; index++{              go handleAccept(L, index)       }       for{              time.Sleep(1e9)       }}func handleAccept(L  net.Listener, index int){       for{              fmt.Println("Accept index=", index)              a, ae := L.Accept()              if ae != nil{                     fmt.Println("Accept index quit", index)                     break              }              go handleConnect(a)       }}func handleConnect(c  net.Conn){       for{              var buffer []byte = make([]byte, 1024)              len, re := c.Read(buffer)              if len == 0 && "EOF" == re.Error(){                     fmt.Println("quit")                     c.Close()                     break              }              var dd string = string(buffer)              fmt.Println(len, re, "data:", dd)       }}

 

用戶端代碼:

package mainimport (       "net"       "time"       "strconv"       "fmt")func Send(){       conn, e := net.Dial("tcp", "127.0.0.1:7878")       if e != nil{              panic("e is nil")       }       var index int = 0       for{              var data string = strconv.Itoa(index)              len, e:=conn.Write([]byte(data))              if e != nil{                     fmt.Println(len, e, "Close Connct")                     conn.Close()              }              index = index+1              time.Sleep(1e9)       }}func main(){       fmt.Println("client main start")       for index:=0; index<100; index++{              go Send()       }       for{              time.Sleep(1e9)       }}

 

 

434 次點擊  ∙  1 贊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.