-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
60 lines (49 loc) · 1.29 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
package giotgo
import (
"fmt"
"net"
"github.com/ghuvrons/g-IoT-Go/giot_packet"
)
type Server struct {
clients []*ClientHandler
setting struct {
clientTimeout int
}
authenticator func(username, password string) bool
commandHandlers map[giot_packet.Command]CommandHandler
commandExecutors map[giot_packet.Command]CommandExecutor
}
func NewServer() *Server {
server := &Server{}
server.commandHandlers = map[giot_packet.Command]CommandHandler{}
server.commandExecutors = map[giot_packet.Command]CommandExecutor{}
return server
}
func (svr *Server) Serve(addr string) {
defer func() {
fmt.Println("server closed")
}()
serverSock, err := net.Listen("tcp", addr)
if err != nil {
fmt.Println(err)
return
}
for true {
conn, err := serverSock.Accept()
if err != nil {
continue
}
fmt.Println("new client")
client := NewClientHandler(&conn, svr, svr.setting.clientTimeout)
svr.clients = append(svr.clients, client)
}
}
func (svr *Server) On(cmd giot_packet.Command, handler CommandHandler) {
svr.commandHandlers[cmd] = handler
}
func (svr *Server) OnExecute(cmd giot_packet.Command, handler CommandExecutor) {
svr.commandExecutors[cmd] = handler
}
func (svr *Server) ClientAuth(authenticator func(username, password string) bool) {
svr.authenticator = authenticator
}