go网络编程-tcp客户端

socket编程    Dial函数 net.Dial()

func Dial(network,addresss string) (Conn, error){

  var d Dialer

  return d.Dial(network,address)

}

//tcp连接

conn,err := net.Dial("tcp","192.168.1.1:8080")

udp 连接

conn ,err := net.Dial("upd","192.168.1.1:8888")

icmp连接

conn , err := net.Dial(“ipv4:icmp”,"www.baidu.com")

conn .err := net.Dial("ipv4:1","www.baidu.com")

 

tcp例子

package main

import (

  "bytes"

  "fmt"

  "io"

  "net"

  "os"

)

func main(){

  if len(os.Args) != 2 {

    fmt.Fprintf(os.Stderr,"usage:%s host port:",os.Args[0])  

  }//

  service  := os.Args[1]

  conn,err := net.Dial("tcp",service)

  checkError(err)

  _,err := conn.Write([]byte("head / http/1.0 \r\n\r\n"))

  checkError(err)

  result,err := readFully(conn)

}

func checkError(err error){

  if err != nil {

    fmt.Fprintf(os.Stderr,"fatal errors:%s",err.error())

    os.Exit(1)

  }

}

func readFully(conn net.Conn)([]byte,error){

  defer conn.Close()

  result := bytes.NewBuffer(nil)

  var buf [512]bytes

}

//就是建立连接、发送数据、接收数据

 

网络超时处理

1连接超时

net.DialTimeout  主动传入额外的超时参数来建立连接

conn,err := net.DialTimeout("tcp",service,3*time.Second )

2请求和响应超时

err =  setDeadline(time.Now().Add(5*time.Second))

        setReadDeadline()

  setWriteDeadline()

net包提供的 

net.ParseIP()

IPv4Mask(a,b,c,d byte)

 

http编程  get post方式发起http请求

http.Client()

http.Get

resp, err :=  http.Get("https://www.baidu.com")

if  err  != nil {

  return 

}

defer resp.Body.Close()

io.Copy(os.Stdout ,resp.Body)

resp.Body 获取响应实体,通过 resp.Header 获取响应头,通过 resp.StatusCode 获取响应状态码

 

http.Post

//参数1  请求的url       参数2    请求数据的资源类型  mineType      参数3   数据的比特流      []byte

resp,err := http.Post("https:www.baidu.com","image/jpeg",&imageDataBuf)

if resp.StatusCode   !=    http.StatsOk {

  

}

 

http.PostForm      application/x-www-form-urlencoded 的post 表单请求

resp,err   :=  http.PostForm("https://www.baidu.com",url.Values{"name":{"fly"}})   ///url.Values  进行编码和封装

 

http.Head      只请求目标url的响应头信息   不返回响应实体

resp , err := http.Head("https://www.baidu.com")

defer resp.Body.Close()

for  key,value := range resp.Header {

  fmt.Println(key,value)

}

 

(*http.Client).Do

http.NewRequest()

req, err   := NewRequest("GET","htttps://www.baidu.com",nil)

if err != nil {

  fmt.Printf()

}

req.Header.Add("key","value")

client :=  &http.Client{

  

}

resp,err := client.Do(req)

 

 

http  https请求处理

开启一个http服务

func ListenAndServer(addr string,handler handler) error

 

package main

func main(){

  http.HandleFunc("/hello",func(writer http.ResponseWriter,rquest *http.Request){

    params := request.URL.Query();

    params.Get("name")

  })

  err := http.ListenAndServe(":80800",nil)

 

客户端请求

req,err  := http.NewRequest("GET","http:/hello?name=fly",nil)

 

}

 

posted @ 2021-04-14 17:56  fly_fly_fly#  阅读(129)  评论(0编辑  收藏  举报