-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
98 lines (80 loc) · 2.21 KB
/
main.go
File metadata and controls
98 lines (80 loc) · 2.21 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// main.go
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/goSeeFuture/hotpot/codec"
"github.com/goSeeFuture/hotpot/hotpot"
"github.com/goSeeFuture/hotpot/network"
"github.com/goSeeFuture/hub"
)
// Echo协议结构
type Echo struct {
Message string
}
// Broadcast广播协议
type Broadcast struct {
Message string
}
func echoServe() {
// 创建websocket服务器
am := network.Serve(
"ws://127.0.0.1:8848",
network.Serialize(codec.JSON),
network.TextMsg(true),
network.Keepalived(60, 80),
)
// 路由Echo消息处理函数
hotpot.Route.Set("Echo", func(data []byte, a hotpot.IAgent) {
// 解析客户端请求
var req Echo
err := am.Serializer().Unmarshal(data, &req)
if err != nil {
fmt.Println("wrong proto")
return
}
fmt.Println("收到客户端消息:", req.Message)
// 返回同样协议内容给客户端
a.WriteMsg(&req)
})
// 监听`广播`调用
hotpot.Global.ListenCall("广播", func(arg interface{}) hub.Return {
var count int
for _, a := range am.Agents() {
count++
a.WriteMsg(&Broadcast{Message: arg.(string)})
}
return hub.Return{Value: count}
})
// 启动服务
am.Start()
fmt.Println("github.com/goSeeFuture/hotpot 服务器就绪,监听地址", am.Listen())
}
func webAPIServe() {
addr := "127.0.0.1:4000"
http.HandleFunc("/broadcast", func(w http.ResponseWriter, req *http.Request) {
msg := req.URL.Query()["msg"]
if len(msg) == 0 {
fmt.Fprintf(w, "缺少msg参数\n使用说明 http://%s/broadcast?msg=这是一条广播消息", addr)
return
}
// 调用Group中的`广播`处理函数,并等待调用返回结果
result, _ := hotpot.Global.Call("广播", msg[0])
fmt.Fprintf(w, "向%d个客户端发送了广播消息", result.Value.(int))
})
fmt.Println("web server 就绪,地址 http://" + addr)
http.ListenAndServe(addr, nil)
}
func main() {
// 启动echo服务
echoServe()
// 启动http服务
go webAPIServe()
// 等待关服信号,如 Ctrl+C、kill -2、kill -3、kill -15
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)
<-ch
}