forked from lonng/nano
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
162 lines (140 loc) · 3.86 KB
/
main.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package main
import (
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/lonng/nano"
"github.com/lonng/nano/component"
"github.com/lonng/nano/pipeline"
"github.com/lonng/nano/scheduler"
"github.com/lonng/nano/serialize/json"
"github.com/lonng/nano/session"
)
type (
Room struct {
group *nano.Group
}
// RoomManager represents a component that contains a bundle of room
RoomManager struct {
component.Base
timer *scheduler.Timer
rooms map[int]*Room
}
// UserMessage represents a message that user sent
UserMessage struct {
Name string `json:"name"`
Content string `json:"content"`
}
// NewUser message will be received when new user join room
NewUser struct {
Content string `json:"content"`
}
// AllMembers contains all members uid
AllMembers struct {
Members []int64 `json:"members"`
}
// JoinResponse represents the result of joining room
JoinResponse struct {
Code int `json:"code"`
Result string `json:"result"`
}
stats struct {
component.Base
timer *scheduler.Timer
outboundBytes int
inboundBytes int
}
)
func (stats *stats) outbound(s *session.Session, msg *pipeline.Message) error {
stats.outboundBytes += len(msg.Data)
return nil
}
func (stats *stats) inbound(s *session.Session, msg *pipeline.Message) error {
stats.inboundBytes += len(msg.Data)
return nil
}
func (stats *stats) AfterInit() {
stats.timer = scheduler.NewTimer(time.Minute, func() {
println("OutboundBytes", stats.outboundBytes)
println("InboundBytes", stats.outboundBytes)
})
}
const (
testRoomID = 1
roomIDKey = "ROOM_ID"
)
func NewRoomManager() *RoomManager {
return &RoomManager{
rooms: map[int]*Room{},
}
}
// AfterInit component lifetime callback
func (mgr *RoomManager) AfterInit() {
session.Lifetime.OnClosed(func(s *session.Session) {
if !s.HasKey(roomIDKey) {
return
}
room := s.Value(roomIDKey).(*Room)
room.group.Leave(s)
})
mgr.timer = scheduler.NewTimer(time.Minute, func() {
for roomId, room := range mgr.rooms {
println(fmt.Sprintf("UserCount: RoomID=%d, Time=%s, Count=%d",
roomId, time.Now().String(), room.group.Count()))
}
})
}
// Join room
func (mgr *RoomManager) Join(s *session.Session, msg []byte) error {
// NOTE: join test room only in demo
room, found := mgr.rooms[testRoomID]
if !found {
room = &Room{
group: nano.NewGroup(fmt.Sprintf("room-%d", testRoomID)),
}
mgr.rooms[testRoomID] = room
}
fakeUID := s.ID() //just use s.ID as uid !!!
s.Bind(fakeUID) // binding session uids.Set(roomIDKey, room)
s.Set(roomIDKey, room)
s.Push("onMembers", &AllMembers{Members: room.group.Members()})
// notify others
room.group.Broadcast("onNewUser", &NewUser{Content: fmt.Sprintf("New user: %d", s.ID())})
// new user join group
room.group.Add(s) // add session to group
return s.Response(&JoinResponse{Result: "success"})
}
// Message sync last message to all members
func (mgr *RoomManager) Message(s *session.Session, msg *UserMessage) error {
if !s.HasKey(roomIDKey) {
return fmt.Errorf("not join room yet")
}
room := s.Value(roomIDKey).(*Room)
return room.group.Broadcast("onMessage", msg)
}
func main() {
components := &component.Components{}
components.Register(
NewRoomManager(),
component.WithName("room"), // rewrite component and handler name
component.WithNameFunc(strings.ToLower),
)
// traffic stats
pip := pipeline.New()
var stats = &stats{}
pip.Outbound().PushBack(stats.outbound)
pip.Inbound().PushBack(stats.inbound)
log.SetFlags(log.LstdFlags | log.Llongfile)
http.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.Dir("web"))))
nano.Listen(":3250",
nano.WithIsWebsocket(true),
nano.WithPipeline(pip),
nano.WithCheckOriginFunc(func(_ *http.Request) bool { return true }),
nano.WithWSPath("/nano"),
nano.WithDebugMode(),
nano.WithSerializer(json.NewSerializer()), // override default serializer
nano.WithComponents(components),
)
}