/
extchannel.go
68 lines (55 loc) · 1.2 KB
/
extchannel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"net/http"
"fmt"
"code.google.com/p/go.net/websocket"
"github.com/m0a/easyjson"
)
//func MakeChanHandleFunc
func channelHandleFunc(
fromClient chan interface{},
toClient chan interface{}) func(w http.ResponseWriter, req *http.Request) {
echoHandler:=func(ws *websocket.Conn){
// ws.JSON.re
for {
select {
case value:=<-fromClient:
// websocket.JSON.Send(ws,value)
// ws.Read(msg)
data,err:=easyjson.NewEasyJson(value)
if err!=nil {
panic("error")
}
fmt.Fprintf(ws,"%s",data)
default:
// JSON.Receive(ws,&data)
// msg := make([]byte, 512)
readdata,err:=easyjson.NewEasyJson(ws)
if err!=nil {
panic("error")
}
toClient<-readdata
}
}
}
return func (w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(echoHandler)}
s.ServeHTTP(w, req)
}
}
func main(){
fmt.Println("Hello...")
readch:=make(chan interface{},1)
writech:=make(chan interface{},1)
http.HandleFunc("/echo",channelHandleFunc(readch,writech))
go func(){
for {
select {
case v := <-writech:
fmt.Println(v)
readch<-fmt.Sprintf("%s", v)
}
}
}()
http.ListenAndServe(":12345",nil)
}