-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserv.go
59 lines (53 loc) · 942 Bytes
/
serv.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
package data
import (
"encoding/json"
"io"
"log"
"net"
"time"
)
type M struct {
Cmd string `json:"cmd,omitempty"`
Key string `json:"key,omitempty"`
Val interface{} `json:"val,omitempty"`
}
type Server struct {
st *Store
}
func InitServer() *Server {
return &Server{
st: InitStore(),
}
}
func (self *Server) Listen(port string) {
ln, err := net.Listen("tcp", port)
if err != nil {
log.Fatal(err)
}
for {
conn, _ := ln.Accept()
go self.Handle(conn)
}
}
func (self *Server) Handle(conn net.Conn) {
enc, dec := json.NewEncoder(conn), json.NewDecoder(conn)
for {
var m M
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
conn.Close()
return
} else {
conn.SetDeadline(time.Now().Add(time.Second * 300))
}
switch m.Cmd {
case "set":
enc.Encode(self.st.Set(&m))
case "get":
enc.Encode(self.st.Get(&m))
default:
enc.Encode(M{Val: "false"})
}
}
}