使用go实现客户端和服务端通讯
客户端:
package main import ( "fmt" "net" "os" ) func main() { conn,err:=net.Dial("tcp","127.0.0.1:9091"); if err == nil { fmt.Println("conn is successful"); } defer conn.Close(); go func() { buf:=make([]byte,1024); for { n, error := os.Stdin.Read(buf); if error != nil { fmt.Println("start is error"); return; } conn.Write(buf[:n]); } }() res := make([]byte, 1024); for { n, err := conn.Read(res); if err != nil { fmt.Println("read is error"); return; } fmt.Printf("data=[%s] ", string(res[:n])); } }
服务端:
package main import ( "fmt" "net" "strings" ) func handleConn (conn net.Conn){ for { addr := conn.RemoteAddr().String(); fmt.Printf("addr=[%s] ", addr); data := make([]byte, 2048); n, err := conn.Read(data); if err != nil { fmt.Println("is error"); return; } str := strings.ToUpper(string(data[:n])); str = strings.Trim(str, " "); conn.Write([]byte(str)); } //defer conn.Close(); } func main() { listener,err:= net.Listen("tcp","127.0.0.1:9091"); if err !=nil { fmt.Println("start is error"); } for { conn,error:=listener.Accept(); if error != nil { fmt.Println("listen is error"); return; } go handleConn(conn); } }