Last active
May 17, 2017 02:40
-
-
Save tupunco/2ba53fe399183f0d40f7 to your computer and use it in GitHub Desktop.
golang_学习
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
//"encoding/json" | |
"fmt" | |
//"os" | |
"sync" | |
"time" | |
) | |
//type Message struct { | |
// Name string `json:"name"` | |
// Body string | |
// Time int64 | |
//} | |
//type User struct { | |
// name string | |
// age int | |
// sex string | |
// phone string | |
//} | |
//func (s *User) SetName(name string) { | |
// s.name = name | |
//} | |
//func (s *User) SetAge(age int) { | |
// s.age = age | |
//} | |
//func (s *User) GetName() string { | |
// return s.name | |
//} | |
//func (s *User) GetAge() int { | |
// return s.age | |
//} | |
//func Try(fun func(), handler func(interface{})) { | |
// defer func() { | |
// if err := recover(); err != nil { | |
// handler(err) | |
// } | |
// }() | |
// fun() | |
//} | |
type WorkerPool struct { | |
tasks <-chan *string //任务队列长度 | |
poolSize int //启动goroutine的数目 | |
} | |
func (p *WorkerPool) Run() { | |
var wg sync.WaitGroup | |
for i := 0; i < p.poolSize; i++ { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
for task := range p.tasks { | |
fmt.Println("Consume Task", *task) | |
} | |
}() | |
} | |
wg.Wait() | |
fmt.Println("WorkerPool | Pool exit.") | |
} | |
func main() { | |
taskNum := 10 | |
projects := make(chan *string, taskNum) | |
//启动生产任务goroutine | |
go func() { | |
for i := 0; i < 101; i++ { | |
s := "Project " + fmt.Sprintf("%d", i) | |
fmt.Println("Produce task", s) | |
projects <- &s | |
time.Sleep(5 * time.Millisecond) | |
} | |
close(projects) | |
}() | |
p := WorkerPool{ | |
tasks: projects, | |
poolSize: 10, | |
} | |
p.Run() | |
fmt.Print("111111") | |
//fmt.Printf("%s-%s", os.Getegid(), os.Args) | |
// Try(func() { | |
// panic(1243) | |
// }, func(e interface{}) { | |
// fmt.Println(e) | |
// }) | |
// // user := User{name: "小强", age: 12, sex: "男", phone: "18656553357"} | |
// // fmt.Printf("user:%s", user) | |
// // user.SetName("笑话") | |
// // fmt.Println(user) | |
// ms := []Message{ | |
// Message{ | |
// Name: "Hello", | |
// Body: "World", | |
// Time: 1234, | |
// }, | |
// Message{ | |
// Name: "Hello", | |
// Body: "World", | |
// Time: 1234, | |
// }, | |
// } | |
// //fmt.Print(ms) | |
// msg, err := json.Marshal(ms) | |
// if err != nil { | |
// panic("111") | |
// return | |
// } | |
// fmt.Printf("%s", msg) | |
// m := Message{ | |
// Name: "a", | |
// Body: "tyt", | |
// Time: 122121, | |
// } | |
// fmt.Printf("%s\r\n", m) | |
// // m := Message{"Alice", "Hello", 1294706395881547000} | |
// // b, err := json.Marshal(m) | |
// // if err != nil { | |
// // panic("error") | |
// // } | |
// // fmt.Println("Hello World!", string(b)) | |
// // fmt.Printf("%s", b) | |
// // fmt.Println("-----------------------\r\n") | |
// dic := make(map[string]interface{}) | |
// dic["Name"] = "Aline" | |
// _, ok := dic["Name"] | |
// if !ok { | |
// panic("11111") | |
// } | |
// dic2 := map[string]interface{}{} | |
// fmt.Println("%s", dic2) | |
// // dic["Name"] = "Alice" | |
// // dic["Body"] = "Hello" | |
// // dic["Time"] = 1294706395881547000 | |
// // dic2 := map[string]interface{}{ | |
// // "Name": "Alice2", | |
// // "Body": "Hello2", | |
// // "Time": 1294706395881547000, | |
// // } | |
// //fmt.Printf("%s-%s", dic, dic2) | |
// b, err := json.Marshal(dic) | |
// if err != nil { | |
// panic("--") | |
// } | |
// fmt.Printf("%s", b) | |
// for k, v := range dic { | |
// fmt.Println(k, v) | |
// } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
//FROM: gorilla_websocket examples | |
import ( | |
"flag" | |
"log" | |
"net/http" | |
"net/url" | |
"time" | |
"github.com/gorilla/websocket" | |
) | |
const ( | |
// Time allowed to write the file to the client. | |
writeWait = 10 * time.Second | |
// Time allowed to read the next pong message from the client. | |
pongWait = 60 * time.Second | |
// Send pings to client with this period. Must be less than pongWait. | |
pingPeriod = (pongWait * 9) / 10 | |
) | |
var ( | |
addr = flag.String("addr", ":9072", "http service address") | |
upgrader = websocket.Upgrader{ | |
ReadBufferSize: 1024, | |
WriteBufferSize: 1024, | |
CheckOrigin: checkSameOrigin, | |
} | |
) | |
func checkSameOrigin(r *http.Request) bool { | |
origin := r.Header["Origin"] | |
if len(origin) == 0 { | |
return true | |
} | |
u, err := url.Parse(origin[0]) | |
log.Printf("checkSameOrigin-%v-%v-%v", u, err, r.Host) | |
return true | |
} | |
func writer(ws *websocket.Conn) { | |
pingTicker := time.NewTicker(pingPeriod) | |
defer func() { | |
pingTicker.Stop() | |
ws.Close() | |
}() | |
for { | |
select { | |
case <-pingTicker.C: | |
ws.SetWriteDeadline(time.Now().Add(writeWait)) | |
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { | |
return | |
} | |
} | |
} | |
} | |
func reader(ws *websocket.Conn) { | |
defer ws.Close() | |
ws.SetReadLimit(512) | |
ws.SetReadDeadline(time.Now().Add(pongWait)) | |
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) | |
for { | |
_, message, err := ws.ReadMessage() | |
if err != nil { | |
log.Println("reader-read:", err) | |
break | |
} | |
log.Printf("reader-recv: %s", message) | |
} | |
} | |
func serveWs(w http.ResponseWriter, r *http.Request) { | |
ws, err := upgrader.Upgrade(w, r, nil) | |
if err != nil { | |
log.Println(err) | |
if _, ok := err.(websocket.HandshakeError); !ok { | |
log.Println(err) | |
} | |
return | |
} | |
log.Printf("---RemoteAddr:%v\r\n", ws.RemoteAddr()) | |
go writer(ws) | |
reader(ws) | |
} | |
func main() { | |
flag.Parse() | |
log.Printf("-----addr-:%v", *addr) | |
http.HandleFunc("/wsTesting/2/1", serveWs) | |
if err := http.ListenAndServe(*addr, nil); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment