参考:https://astaxie.gitbooks.io/build-web-application-with-golang/zh/08.1.html

客户端

操作步骤:

  • 确定服务器的IP和端口号
  • 建立TCP连接
  • 向服务器发送请求
  • 接收请求
服务端

操作步骤:

  • 确定监听的端口号
  • 启动TCP监听
  • 接收客户端的请求
  • 返回数据(可以在单独的协程中完成)
代码实例

客户端:

package mainimport("net""os""fmt""io/ioutil"
)func main(){if len(os.Args)!=2{fmt.Println(os.Stderr,"Usage:%s host:port ",os.Args[0])os.Exit(1)}service:=os.Args[1]tcpAddr,err:=net.ResolveTCPAddr("tcp4",service)  conn,err:=net.DialTCP("tcp",nil,tcpAddr)checkErr(err)_,err=conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))checkErr(err)result,err:=ioutil.ReadAll(conn)checkErr(err)fmt.Println(string(result))os.Exit(0)
}func checkErr(err error){if err!=nil{fmt.Fprintf(os.Stderr,"Fatal error: %s\n",err.Error())os.Exit(1)}
}

服务端:

package mainimport("fmt""net""os""time"
)func main(){service:=":7777"tcpAddr,err:=net.ResolveTCPAddr("tcp4",service)checkErr(err)listener,err:=net.ListenTCP("tcp",tcpAddr)checkErr(err)for{conn,err:=listener.Accept()if err!=nil{continue;}go handleClient(conn)}
}func checkErr(err error){if err!=nil{fmt.Fprintf(os.Stderr,"Fatal error: %s",err.Error())}
}func handleClient(conn net.Conn){defer conn.Close()daytime:=time.Now().String()conn.Write([]byte(daytime))
}