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
69
70
71
72
73
74
75
| // server.go
/*
golang中使用的是http1.1协议,默认为长链接。仅第一次发送请求时进行握手。
*/
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"sync"
"github.com/gorilla/websocket"
)
var ws_addr = flag.String("ws_addr", "localhost:9080", "websocket http service address")
var http_addr = flag.String("http_addr", "localhost:9090", "http address address")
var upgrader = websocket.Upgrader{} // use default options
func ws_echo(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}
}
func http_echo(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
echo_data := req.Form.Get("echo")
fmt.Println(echo_data)
io.WriteString(w, echo_data)
return
}
func start_websocket() {
http.HandleFunc("/ws_echo", ws_echo)
log.Fatal(http.ListenAndServe(*ws_addr, nil))
}
func start_http() {
http.HandleFunc("/http_echo", http_echo)
log.Fatal(http.ListenAndServe(*http_addr, nil))
}
func main() {
flag.Parse()
log.SetFlags(0)
wg := sync.WaitGroup{}
wg.Add(2)
go start_websocket()
go start_http()
wg.Wait()
}
|