server.go
package main import ( "net" "fmt" "io/ioutil" "time" ) func main(){ tcpServer, _ := net.ResolveTCPAddr("tcp4", ":8080") listener, _ := net.ListenTCP("tcp", tcpServer) for { conn, err := listener.Accept() if err != nil { fmt.Println(err) continue } // handle go handle(conn) } } func handle(conn net.Conn){ defer conn.Close() //read msg from client go func(){ response, _ := ioutil.ReadAll(conn) fmt.Println(response) }() // send msg to client time.Sleep(1 * time.Second) now := time.Now().String() conn.Write([]byte(now)) }
client.go
package main import ( "os" "fmt" "net" "io/ioutil" ) func main() { if len(os.Args) < 2 { fmt.Fprintf(os.Stderr, "Usage: %s host:port", os.Args[0]) } // get socket addr from ags server := os.Args[1] addr, err := net.ResolveTCPAddr("tcp4", server) checkError(err) // establish conn conn, err := net.DialTCP("tcp4", nil, addr) checkError(err) // send msg to server _, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n")) checkError(err) //get response response, _ := ioutil.ReadAll(conn) fmt.Println(string(response)) os.Exit(0) } func checkError(err error){ if err != nil{ fmt.Println(err) os.Exit(1) } }
原文:https://studygolang.com/articles/11796
有疑问加站长微信联系(非本文作者)