十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章将为大家详细讲解有关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实现 就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。