golang實現tcp通訊例子
tcp/udp ip通訊是當前重要的通訊方式。
當然對於golang開發者而言,實現tcp通訊也是必要的。本文的內容主要是基於《Go語言四十二章經》簡書地址:https://www.jianshu.com/nb/29056963 的詳細講解
本文的例子分為服務端與客戶端兩部分:
服務端:
package main import ( "bufio" "fmt" "io" "net" "time" ) //tcp server 服務端程式碼 func main() { //定義一個tcp斷點 var tcpAddr *net.TCPAddr //通過ResolveTCPAddr例項一個具體的tcp斷點 tcpAddr,_ = net.ResolveTCPAddr("tcp","127.0.0.1:9999") //開啟一個tcp斷點監聽 tcpListener,_ := net.ListenTCP("tcp",tcpAddr) defer tcpListener.Close() fmt.Println("Server ready to read ...") //迴圈接收客戶端的連線,建立一個協程具體去處理連線 for{ tcpConn,err := tcpListener.AcceptTCP() if err!=nil { fmt.Println(err) continue } fmt.Println("A client connected :" +tcpConn.RemoteAddr().String()) go tcpPipe(tcpConn) } } //具體處理連線過程方法 func tcpPipe(conn *net.TCPConn){ //tcp連線的地址 ipStr := conn.RemoteAddr().String() defer func() { fmt.Println(" Disconnected : " + ipStr) conn.Close() }() //獲取一個連線的reader讀取流 reader := bufio.NewReader(conn) i:=0 //接收並返回訊息 for { message,err := reader.ReadString('\n') if err!=nil || err == io.EOF { break } fmt.Println(string(message)) time.Sleep(time.Second*3) msg := time.Now().String() + conn.RemoteAddr().String() + " Server Say hello! \n" b := []byte(msg) conn.Write(b) i++ if i>10 { break } } }
客戶端
package main import ( "bufio" "fmt" "io" "net" "time" ) func main() { var tcpAddr *net.TCPAddr tcpAddr,_ = net.ResolveTCPAddr("tcp","127.0.0.1:9999") conn,err := net.DialTCP("tcp",nil,tcpAddr) if err!=nil { fmt.Println("Client connect error ! " + err.Error()) return } defer conn.Close() fmt.Println(conn.LocalAddr().String() + " : Client connected!") onMessageReceived(conn) } func onMessageReceived(conn *net.TCPConn) { reader := bufio.NewReader(conn) b := []byte(conn.LocalAddr().String() + " Say hello to Server... \n") conn.Write(b) for { msg, err := reader.ReadString('\n') fmt.Println("ReadString") fmt.Println(msg) if err != nil || err == io.EOF { fmt.Println(err) break } time.Sleep(time.Second * 2) fmt.Println("writing...") b := []byte(conn.LocalAddr().String() + " write data to Server... \n") _, err = conn.Write(b) if err != nil { fmt.Println(err) break } } }