server端:
package main
import (
"net/http"
"fmt"
"io/ioutil"
)
func IndexHandler(w http.ResponseWriter, req *http.Request) {
fmt.Println("-------------------")
fmt.Println(w, "hello world")
body, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Println("read all error")
return
}
fmt.Println(">>", string(body))
}
func main() {
http.HandleFunc("/", IndexHandler)
fmt.Println("start")
err := http.ListenAndServe("127.0.0.1:19988", nil)
if err != nil {
fmt.Println("err:", err)
return
}
fmt.Println("end")
}
client端:
package main
import (
"fmt"
"net/http"
"time"
"net"
"encoding/json"
"strings"
)
func main() {
connTimeout := 2*time.Millisecond
readTimeout := 3*time.Millisecond
client := http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout("tcp4", addr, connTimeout)
if err != nil {
return nil, err
}
c.SetDeadline(time.Now().Add(readTimeout))
return c, nil
},
},
}
for i:=0; i<100; i++ {
postParams := map[string]interface{}{"checksum": "1111111111111", "result": "penggetest"}
bytebody, _ := json.Marshal(postParams)
retbody := string(bytebody)
req, err := http.NewRequest("POST", "http://127.0.0.1:19988/", strings.NewReader(retbody))
if err != nil {
fmt.Println("new request err:", err)
return
}
headers := make(map[string]string)
for key, value := range headers {
req.Header.Set(key, value)
}
resp, reqErr := client.Do(req)
if reqErr != nil {
fmt.Println(" client do err:", reqErr)
return
}
defer resp.Body.Close()
fmt.Println("code:", resp.StatusCode, "\nerr:", err)
time.Sleep(2*time.Second)
}
}
运行服务端:
运行客户端: