Go语言练习 TCPserver 与 TCPclient实现
serverTcp.go
1 package main 2 3 import ( 4 "net" 5 "fmt" 6 "os" 7 "time" 8 ) 9 10 func checkError(err error){ 11 if err != nil { 12 fmt.Fprintf(os.Stderr,"Fatal error: %s",err.Error()) 13 os.Exit(1) 14 } 15 } 16 17 func handleConnection(conn net.Conn,i int){ 18 fmt.Println("connect succeed! ID: ",i) 19 i += 1 20 time.Sleep(1* time.Millisecond) 21 _,_ = conn.Write([]byte("message from server\r\n\r\n")) 22 time.Sleep(1* time.Millisecond) 23 conn.Close() 24 } 25 func main() { 26 i := 0 27 ln,err := net.Listen("tcp",":8080") 28 checkError(err) 29 30 for { 31 conn,err := ln.Accept() 32 if err != nil { 33 fmt.Fprintf(os.Stderr,"Fatal error: %s",err.Error()) 34 continue 35 } 36 i += 1 37 go handleConnection(conn,i) 38 } 39 }
clientTcp.go
package main import ( "fmt" "os" "net" "time" "io" ) func checkError(err error){ if err != nil { fmt.Fprintf(os.Stderr,"Fatal error: %s",err.Error()) os.Exit(1) } } func main() { for i:=0 ;i <100 ;i++{ conn,err := net.Dial("tcp","127.0.0.1:8080") checkError(err) fmt.Println("connect succeed! ID:",i+1) var buf [512]byte for { _,err := conn.Read(buf[0:]) if err != nil { if err == io.EOF { break } } } fmt.Println(string(buf[:])) time.Sleep(1* time.Millisecond) conn.Close() } }