您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關tcp的server端與client端怎么利用golang實現 ,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
server端代碼:
package main import ( "fmt" "net" "log" "os" ) func main() { addr := "0.0.0.0:8787" tcpAddr, err := net.ResolveTCPAddr("tcp",addr) if err != nil { log.Fatalf("net.ResovleTCPAddr fail:%s", addr) //等價于print err后,再os.Exit(1) } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { log.Fatalf("listen %s fail: %s", addr, err) }else { log.Println("rpc listening", addr) } for { conn, err := listener.Accept() if err != nil { log.Println("listener.Accept error:", err) continue } go handle_Client(conn) } } func handle_Client(conn net.Conn) { defer conn.Close() var write_buffer []byte = []byte("ok") read_buffer := make([]byte, 128) n, err1 := conn.Read(read_buffer) if err1 != nil { fmt.Println("ser Read failed:", err1) os.Exit(1) } m, err2 := conn.Write(write_buffer) if err2 != nil { fmt.Println("ser send error:", err2) os.Exit(1) } fmt.Println("ser read cli send data count:", n, "msg:", string(read_buffer)) fmt.Println("ser send data to cli count:", m, "msg:", string(write_buffer)) fmt.Println("********one connetion end*********") }
client端代碼:
package main import ( "fmt" "net" "os" "time" ) func main() { conn, err := net.Dial("tcp", "127.0.0.1:8787") if err != nil { fmt.Println("dial failed:", err) os.Exit(1) } defer conn.Close() var write_buffer []byte = []byte("Hi,server. I'm client.") read_buffer := make([]byte, 128) start_time := time.Now() n, err2 := conn.Write(write_buffer) if err2 != nil { fmt.Println("cli send error:", err2) os.Exit(1) } m, err1 := conn.Read(read_buffer) if err1 != nil { fmt.Println("cli Read failed:", err1) os.Exit(1) } response_time := time.Since(start_time) RTT_time := float64(response_time.Nanoseconds()) / 1e+06 //ns-->ms fmt.Println(RTT_time) fmt.Println("cli send data to ser count:", n, "msg:", string(write_buffer)) fmt.Println("cli read ser data count:", m, "msg:", string(read_buffer)) }
補充:go 語言 TCP服務器接受客戶端字符串信息
我就廢話不多說了,大家還是直接看代碼吧~
func hand_conn(conn net.Conn) ([]byte){ defer conn.Close() //clientarr := conn.RemoteAddr() //獲取連接到的對像的IP地址 result := bytes.NewBuffer(nil) var buf [512]byte for { n, err := conn.Read(buf[0:]) result.Write(buf[0:n]) if err != nil { if err == io.EOF { break } } } //explan_rec_infos(string(result.Bytes())) return result.Bytes() } func main() { fmt.Println("Hello World! go server") server, err := net.Listen("tcp", ":9993") if err == nil { //若果err為nil,則成功創建 index := 1 for { index++ con, _ := server.Accept() fmt.Println("有一個客戶連接" , index) hand_conn(con) } } else { return } }
關于tcp的server端與client端怎么利用golang實現 就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。