GO tcp服务器编程 socket编程
//server.go package main import ( "fmt" "math/rand" "net" "strconv" ) func main(){ listener,err := net.Listen("tcp",":8080") if err != nil { fmt.Println("listen error:",err) return } for { conn,err := listener.Accept() if err != nil { fmt.Println("accept error:",err) continue } go Handle(conn) } } func Handle(conn net.Conn){ go Read(conn) go Write(conn) } func Read(conn net.Conn){ a := make([]byte,100) conn.Read(a) fmt.Println("recv data:",string(a)) } func Write(conn net.Conn){ b := []byte("i am fly"+ strconv.Itoa(rand.Int())) conn.Write(b) fmt.Println("send data:",string(b)) }
//client.go package main import ( "fmt" "net" "strconv" "time" ) func main(){ i := 0 for { conn,err := net.DialTimeout("tcp","127.0.0.1:8080",10*time.Second) if err != nil { fmt.Println("Dial error:",err) return } a := make([]byte,100) conn.Read(a) fmt.Println("read data :",string(a)) conn.Write([]byte("i am client:"+strconv.Itoa(i))) i++ } }