Let's make some fun to simulation Server - Client.
1. socket
I implement a echo server and use telnet to simulate the socket client.
in this way, we don't need to implement our socket client but can test our client server in a standard way.
It can support multiple telnet clients concurrently. The behavior is as bellow.
when user input "BYE", the connect to server shuts down.
code snippet:
1 package main 2 3 import ( 4 "bufio" 5 "fmt" 6 "io" 7 "log" 8 "net" 9 "strings" 10 ) 11 12 func main() { 13 // Listen on TCP port 2000 on all interfaces. 14 l, err := net.Listen("tcp", ":2000") 15 if err != nil { 16 log.Fatal(err) 17 } 18 defer l.Close() 19 20 for { 21 // Wait for a connection. 22 conn, err := l.Accept() 23 if err != nil { 24 log.Fatal(err) 25 } 26 fmt.Println("INFO: accept a client") 27 28 // Handle the connection in a new goroutine. 29 go func(c net.Conn) { 30 defer c.Close() 31 32 rd := bufio.NewReader(c) 33 for { 34 line, _, err := rd.ReadLine() 35 if err != nil && err != io.EOF { 36 log.Fatal(err) 37 } 38 39 s := string(line) 40 fmt.Println("LOG:", s) 41 42 //since rd.ReadLine() has trimed last " ", append here to echo 43 _, err = conn.Write([]byte("ECHO:" + s + " ")) 44 if err != nil { 45 log.Fatal(err) 46 } 47 48 if strings.ToLower(s) == "bye" { 49 fmt.Println("INFO: client closed") 50 break 51 } 52 } 53 }(conn) 54 } 55 }
2. http.Client