golang net package simulation

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

Let's make some fun to simulation  Server - Client.

 

1.  socket

I implement a echo server and use telnet to simulate the socket client.

in this way,  we don't need to implement our socket client but can test our client server in a standard way.

It can support multiple telnet clients concurrently. The behavior is as bellow.

when user input "BYE",  the connect to server shuts down.

code snippet:

 1 package main 2  3 import ( 4     "bufio" 5     "fmt" 6     "io" 7     "log" 8     "net" 9     "strings"10 )11 12 func main() {13     // Listen on TCP port 2000 on all interfaces.14     l, err := net.Listen("tcp", ":2000")15     if err != nil {16         log.Fatal(err)17     }18     defer l.Close()19 20     for {21         // Wait for a connection.22         conn, err := l.Accept()23         if err != nil {24             log.Fatal(err)25         }26         fmt.Println("INFO: accept a client")27 28         // Handle the connection in a new goroutine.29         go func(c net.Conn) {30             defer c.Close()31 32             rd := bufio.NewReader(c)33             for {34                 line, _, err := rd.ReadLine()35                 if err != nil && err != io.EOF {36                     log.Fatal(err)37                 }38 39                 s := string(line)40                 fmt.Println("LOG:", s)41 42                 //since rd.ReadLine() has trimed last "\n", append here to echo43                 _, err = conn.Write([]byte("ECHO:" + s + "\r\n"))44                 if err != nil {45                     log.Fatal(err)46                 }47 48                 if strings.ToLower(s) == "bye" {49                     fmt.Println("INFO: client closed")50                     break51                 }52             }53         }(conn)54     }55 }

 

2. http.Client

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.