Golang實現簡單tcp伺服器02 -- 實現echo伺服器/用戶端

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

用Golang實現 echo伺服器/用戶端

本節我們就從實現一個簡單的echo的服務端/用戶端來入手, 瞭解golang的實現tcp長串連伺服器的具體細節.

首先, 我們先列一下**服務端的實現思路及步驟**:
1. 建立一個通訊端對象, 指定其IP以及連接埠.
2. 開始監聽通訊端指定的連接埠.
3. 如有新的用戶端串連請求, 則建立一個goroutine, 在goroutine中, 讀取用戶端訊息, 並轉寄回去, 直到用戶端中斷連線
4. 主進程繼續監聽連接埠.

我們可以在實驗環境的主資料夾中, 建立一個名為server.go的檔案, 在其中編寫伺服器端程式碼
服務端程式清單如下:

server.go

package mainimport (    "bufio"    "fmt"    "net"    "time")func main() {    var tcpAddr *net.TCPAddr    tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")    tcpListener, _ := net.ListenTCP("tcp", tcpAddr)    defer tcpListener.Close()    for {       tcpConn, err := tcpListener.AcceptTCP()       if err != nil {         continue       }       fmt.Println("A client connected : " + tcpConn.RemoteAddr().String())       go tcpPipe(tcpConn)    }}func tcpPipe(conn *net.TCPConn) {    ipStr := conn.RemoteAddr().String()    defer func() {       fmt.Println("disconnected :" + ipStr)       conn.Close()    }()    reader := bufio.NewReader(conn)    for {       message, err := reader.ReadString('\n')       if err != nil {         return       }       fmt.Println(string(message))       msg := time.Now().String() + "\n"       b := []byte(msg)       conn.Write(b)    }}

接著, 我們開啟終端, 編譯服務端程式:

go build server.go

編譯成功的話, 會在主目錄中看到編譯成功的server程式

接下來, 是**用戶端的代碼實現步驟**:
1. 建立一個通訊端對象, ip與連接埠指定到上面我們實現的伺服器的ip與連接埠上.
2. 使用建立好的通訊端對象串連伺服器.
3. 串連成功後, 開啟一個goroutine, 在這個goroutine內, 定時的向伺服器發送訊息, 並接受伺服器的返回訊息, 直到錯誤發生或中斷連線.

程式清單如下:

client.go

package mainimport (    "bufio"    "fmt"    "net"    "time")var quitSemaphore chan boolfunc main() {    var tcpAddr *net.TCPAddr    tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")    conn, _ := net.DialTCP("tcp", nil, tcpAddr)    defer conn.Close()    fmt.Println("connected!")    go onMessageRecived(conn)    b := []byte("time\n")    conn.Write(b)    <-quitSemaphore}func onMessageRecived(conn *net.TCPConn) {    reader := bufio.NewReader(conn)    for {       msg, err := reader.ReadString('\n')       fmt.Println(msg)       if err != nil {         quitSemaphore <- true         break       }       time.Sleep(time.Second)       b := []byte(msg)       conn.Write(b)    }}

編譯用戶端:

go build client.go

最後, 開啟兩個終端, 分別運行server和client

可以看到以下類似的輸出:

connected!
2015-03-19 23:42:08.4875559 +0800 CST

2015-03-19 23:42:09.4896132 +0800 CST

2015-03-19 23:42:10.4906704 +0800 CST

2015-03-19 23:42:11.4917277 +0800 CST

2015-03-19 23:42:12.4927849 +0800 CST

2015-03-19 23:42:13.4938422 +0800 CST

2015-03-19 23:42:14.4948995 +0800 CST

2015-03-19 23:42:15.4959567 +0800 CST

2015-03-19 23:42:16.497014 +0800 CST

2015-03-19 23:42:17.4980712 +0800 CST

2015-03-19 23:42:18.4991285 +0800 CST

2015-03-19 23:42:19.5001857 +0800 CST

這樣, 一個簡單的echo伺服器/用戶端就實現了

聯繫我們

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