package main import ( "bufio" "fmt" "log" "net" "os" "strings" ) //TCP server端 func process(conn net.Conn) { defer conn.Close() var tmp = make([]byte, 1024) reader := bufio.NewReader(os.Stdin) for { n, err := conn.Read(tmp) if err != nil { log.Fatal("read failed on:", err) return } fmt.Println(string(tmp[:n])) fmt.Print("请回复:") msg, _ := reader.ReadString('\n') msg = strings.TrimSpace(msg) if msg == "exit" { break } conn.Write([]byte(msg)) fmt.Println("等待回复中..") } } func main() { //1.本地端口启动服务 listener, err := net.Listen("tcp", "127.0.0.1:20000") if err != nil { log.Fatal("start Tcp server failed on:", err) return } //2.等待别人来跟我建立链接 for { conn, err := listener.Accept() if err != nil { log.Fatal("accept failed on:", err) } //3与客户端通信 go process(conn) } }