server.gohtml
package main import ( "fmt" "net" ) func process(conn net.Conn) { defer conn.Close() for { buf := make([]byte, 1024) fmt.Println("服務器在等待客戶端發送信息"+conn.RemoteAddr().String()) n, err := conn.Read(buf) if err != nil { fmt.Printf("服務器端read error =", err) return } // 顯示客戶端發送的內容到服務器的終端 fmt.Print(string(buf[:n])) } } func main() { listen, err := net.Listen("tcp","0.0.0.0:8888") if err != nil { fmt.Println("listen err = ", err) } // 延時關閉 defer listen.Close() for { // 等待客戶端鏈接 fmt.Println("等待客戶端來鏈接") con, err := listen.Accept() if err != nil { fmt.Println("connect err = ", err) } fmt.Printf("connect success %v, 客戶端IP = %v", con, con.RemoteAddr().String()) go process(con) } fmt.Printf("listen = %v", listen) }
client.go服務器
package main import ( "bufio" "fmt" "net" "os" ) func main() { conn, err := net.Dial("tcp", "0.0.0.0:8888") if err != nil { fmt.Println("client dial err = ", err) return } reader := bufio.NewReader(os.Stdin) line, err := reader.ReadString('\n') if err != nil { fmt.Println("read string err=", err) } n , err := conn.Write([]byte(line)) if err != nil { fmt.Println("connect write = ", err) } fmt.Println("客戶端發送了%d的字節, 並退出", n) }