go http 客户端

 1 package main
 2 import (
 3     "net/http"
 4     "time"
 5     "math/rand"
 6     "io/ioutil"
 7     "net/url"
 8     "strings"
 9     "fmt"
10 )
11 func randString() string {
12     var s []byte
13     for l:= rand.Uint32()%10+1; l>0 ;l-- {
14         s = append(s,uint8(rand.Uint32()%26+'a'));
15     }
16     //println("rand",string(s))
17     return string(s)
18 }
19 var ch chan int
20 func post(id int) {
21     println("run post",id)
22     username := randString()
23     password := randString()
24     resp,_ := http.PostForm("http://127.0.0.1:8080/login",url.Values{"username" : {username}, "password" : {password}})
25     println("login    username:",username,"password:",password)
26     if resp == nil {
27         println("login fail")
28         return
29     }
30     println(resp.StatusCode)
31     resp.Body.Close();
32     post1(username)
33 }
34 func post1(s string) {
35     //ch<-1
36     for true{
37         time.Sleep(time.Second * 10)
38         resp,_ := http.PostForm("http://127.0.0.1:8080/check",url.Values{"username" : {s}})
39         if resp == nil {
40             println("post1 no response")
41             return
42         }
43         defer resp.Body.Close();
44         println("check online :",s)
45     }
46 }
47 func DoRequest() {
48     for i:=0; i< 100; i++ {
49         transport := http.Transport{
50             DisableKeepAlives : true, //传输完关闭http连接
51         }
52         client := &http.Client{
53             Transport : &transport,
54         }
55     
56         username := randString()
57         password := randString()
58         req, err := http.NewRequest("POST", "http://127.0.0.1:8080/login", 
59         strings.NewReader(url.Values{"username" : {username}, "password" : {password}}.Encode()))
60         if err != nil {
61             println("error:",err.Error())
62         }
63     
64         req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
65         req.Header.Set("Cookie", "name=anny")
66         req.Header.Set("username",username)
67         req.Header.Set("password",password)
68         println("login    username:",username,"password:",password)
69         resp, err := client.Do(req)
70         if err != nil {
71             println("error:",err.Error())
72         }
73         if resp == nil {
74             println("login no response")
75             return
76         }
77         defer resp.Body.Close()
78     
79         body, err := ioutil.ReadAll(resp.Body)
80         if err != nil {
81             println("error:",err.Error())
82         }
83     
84         fmt.Println(string(body))
85         go post1(username)
86     }
87 }
88 func main()  {
89     //ch=make(chan int,100000)
90     for i:=0 ;i<10;i++ {
91          go DoRequest()
92     }
93     for true {
94     //    if len(ch) > 10000 {
95     //        println(len(ch))
96     //    }
97     }
98 }
client.go(轮询)
 1 package main
 2 
 3 import (
 4     "fmt"
 5     "sync"
 6     //"os"
 7     "html/template"
 8     "net/http"
 9     //    "database/sql"
10 
11     "time"
12 
13     _ "github.com/lib/pq"
14     //"log"
15 )
16 
17 var mutex sync.Mutex
18 var Online_table map[string]time.Time
19 
20 func ToString(s []string) string {
21     n := len(s)
22     var result string = ""
23     for i := 0; i < n; i++ {
24         result = result + s[i]
25     }
26     return result
27 }
28 func Login(w http.ResponseWriter, req *http.Request) {
29     out(req)
30     err := req.ParseForm() //一定要先处理
31     if err != nil {
32         w.Write([]byte("出错了!" + err.Error()))
33         return
34     }
35     //fmt.Println(req.URL)
36     username := ToString(req.Form["username"])
37     password := ToString(req.Form["password"])
38 
39     println("username:", username, "password:", password)
40     Online_table[username] = time.Now().Add(10 * time.Second)
41 }
42 
43 func out(req *http.Request) {
44     fmt.Println("get", req.URL.Path, " from ", req.RemoteAddr)
45 }
46 func repeatCheck() {
47 
48     for {
49         timeNow := time.Now()
50         mutex.Lock()
51         //hour,min,sec := timeNow.Clock()
52         //fmt.Println("timeNow:",hour,min,sec)
53         for key, val := range Online_table {
54             if val.Before(timeNow) {
55                 delete(Online_table, key)
56                 fmt.Println("delete", key)
57             }
58         }
59         fmt.Println("-------------------------", len(Online_table), "are online")
60         mutex.Unlock()
61         //fmt.Println("sleeping")
62         time.Sleep(20 * time.Second)
63     }
64 }
65 func Index(w http.ResponseWriter, req *http.Request) {
66     out(req)
67     t, err := template.ParseFiles("../index.html")
68     if err != nil {
69         w.Write([]byte("出错了: " + err.Error()))
70     }
71     t.Execute(w, nil)
72 
73 }
74 func IsOnline(w http.ResponseWriter, req *http.Request) {
75     out(req)
76     req.ParseForm()
77 }
78 func Check(w http.ResponseWriter, req *http.Request) {
79     out(req)
80     req.ParseForm()
81     username := ToString(req.Form["username"])
82 
83     mutex.Lock()
84     Online_table[username] = time.Now().Add(time.Second * 20)
85     mutex.Unlock()
86 }
87 
88 func main() {
89     Online_table = make(map[string]time.Time)
90     go repeatCheck()
91     http.HandleFunc("/check", Check)
92     http.HandleFunc("/", Index)
93     http.HandleFunc("/login", Login)
94     http.ListenAndServe(":8080", nil)
95 }
server.go(轮询)
 1 package main  
 2   
 3 import (  
 4     "fmt"  
 5     "io/ioutil"  
 6     "net/http"  
 7 )  
 8   
 9 func main() {  
10     response, _ := http.Get("http://localhost:80/hello")  
11     defer response.Body.Close()  
12     body, _ := ioutil.ReadAll(response.Body)  
13     fmt.Println(string(body))  
14 }  
client(Get)

基于 HTTP 长连接的“服务器推”技术

http://blog.csdn.net/rosen_luo/article/details/46682411 

原文地址:https://www.cnblogs.com/cdyboke/p/6565623.html