server端
main.go
package main import ( "fmt" "net" ) func main() { // simple tcp server //1.listen ip+port listener, err := net.Listen("tcp", "0.0.0.0:9090") if err != nil { fmt.Printf("listen fail, err: %v ", err) return } //2.accept client request //3.create goroutine for each request for { conn, err := listener.Accept() if err != nil { fmt.Printf("accept fail, err: %v ", err) continue } //create goroutine for each connect go process(conn) } } func process(conn net.Conn) { defer conn.Close() for { var buf [128]byte n, err := conn.Read(buf[:]) if err != nil { fmt.Printf("read from connect failed, err: %v ", err) break } str := string(buf[:n]) fmt.Printf("receive from client, data: %v ", str) } }
client端
main.go
package main import ( "bufio" "fmt" "net" "os" "strings" ) func main() { conn, err := net.Dial("tcp", "localhost:9090") defer conn.Close() if err != nil { fmt.Printf("connect failed, err : %v ", err.Error()) return } inputReader := bufio.NewReader(os.Stdin) for { input, err := inputReader.ReadString(' ') if err != nil { fmt.Printf("read from console failed, err: %v ", err) break } trimmedInput := strings.TrimSpace(input) if trimmedInput == "Q" { break } _, err = conn.Write([]byte(trimmedInput)) if err != nil { fmt.Printf("write failed , err : %v ", err) break } } }
分别编译执行服务端和客户端
客户端通过命令行与服务端简单交互