package main //*********************************server***************************************** import ( "fmt" "net" "bufio" ) func main() { listener , err := net.Listen("tcp",":8000");//listen localhost:8000 if err != nil { return; } for{ conn,err := listener.Accept();// wait for accept if err != nil { fmt.Printf("%s\n",err); continue; } go handler(conn);// create a thread } } func handler(conn net.Conn){ fmt.Printf("accepted !\n"); fmt.Printf("%s\n",conn.LocalAddr().String()); buf ,err:= bufio.NewReader(conn).ReadString('\n'); fmt.Fprintf(conn,"HTTP 1.1 ok \r\n"); for err == nil { fmt.Printf("%s",buf); buf,err = bufio.NewReader(conn).ReadString('\n'); } }
//********************************************client**********************************************************************
package main import ( "fmt" "net" "bufio" ) func main(){ var err error ; var conn net.Conn; conn , err = net.Dial("tcp","localhost:8000");//connect to localhost:8000 if err != nil { fmt.Printf("%s\n",err); return ; } fmt.Printf("connected!\n"); fmt.Fprintf(conn,"GET / HTTP 1.1 \r\n\r\n"); var in * bufio.Reader; in = bufio.NewReader(conn); str , err := in.ReadString('\n'); if err != nil { return ; } fmt.Printf("%s",str); }
有疑问加站长微信联系(非本文作者)