golang 实现tcp server端和client端,并计算RTT时间操作
(编辑:jimmy 日期: 2024/11/9 浏览:3 次 )
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 } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
下一篇:golang的time包:秒、毫秒、纳秒时间戳输出方式