forked from funny/link
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
65 lines (53 loc) · 1.21 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
package link
import "net"
type Server struct {
manager *Manager
listener net.Listener
protocol Protocol
handler Handler
sendChanSize int
}
type Handler interface {
HandleSession(*Session)
}
var _ Handler = HandlerFunc(nil)
type HandlerFunc func(*Session)
func (f HandlerFunc) HandleSession(session *Session) {
f(session)
}
func NewServer(listener net.Listener, protocol Protocol, sendChanSize int, handler Handler) *Server {
return &Server{
manager: NewManager(),
listener: listener,
protocol: protocol,
handler: handler,
sendChanSize: sendChanSize,
}
}
func (server *Server) Listener() net.Listener {
return server.listener
}
func (server *Server) Serve() error {
for {
conn, err := Accept(server.listener)
if err != nil {
return err
}
go func() {
codec, err := server.protocol.NewCodec(conn)
if err != nil {
conn.Close()
return
}
session := server.manager.NewSession(codec, server.sendChanSize)
server.handler.HandleSession(session)
}()
}
}
func (server *Server) GetSession(sessionID uint64) *Session {
return server.manager.GetSession(sessionID)
}
func (server *Server) Stop() {
server.listener.Close()
server.manager.Dispose()
}