forked from klintcheng/kim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
78 lines (66 loc) · 1.7 KB
/
server.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
package mock
import (
"errors"
"net/http"
_ "net/http/pprof"
"time"
"github.com/klintcheng/kim"
"github.com/klintcheng/kim/logger"
"github.com/klintcheng/kim/naming"
"github.com/klintcheng/kim/tcp"
"github.com/klintcheng/kim/websocket"
)
type ServerDemo struct{}
func (s *ServerDemo) Start(id, protocol, addr string) {
go func() {
_ = http.ListenAndServe("0.0.0.0:6060", nil)
}()
var srv kim.Server
service := &naming.DefaultService{
Id: id,
Protocol: protocol,
}
if protocol == "ws" {
srv = websocket.NewServer(addr, service)
} else if protocol == "tcp" {
srv = tcp.NewServer(addr, service)
}
handler := &ServerHandler{}
srv.SetReadWait(time.Minute)
srv.SetAcceptor(handler)
srv.SetMessageListener(handler)
srv.SetStateListener(handler)
err := srv.Start()
if err != nil {
panic(err)
}
}
// ServerHandler ServerHandler
type ServerHandler struct {
}
// Accept this connection
func (h *ServerHandler) Accept(conn kim.Conn, timeout time.Duration) (string, kim.Meta, error) {
// 1. 读取:客户端发送的鉴权数据包
frame, err := conn.ReadFrame()
if err != nil {
return "", nil, err
}
// 2. 解析:数据包内容就是userId
userID := string(frame.GetPayload())
// 3. 鉴权:这里只是为了示例做一个fake验证,非空
if userID == "" {
return "", nil, errors.New("user id is invalid")
}
logger.Infof("logined %s", userID)
return userID, nil, nil
}
// Receive default listener
func (h *ServerHandler) Receive(ag kim.Agent, payload []byte) {
logger.Infof("srv received %s", string(payload))
_ = ag.Push([]byte("ok"))
}
// Disconnect default listener
func (h *ServerHandler) Disconnect(id string) error {
logger.Infof("disconnect %s", id)
return nil
}