-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudpserver.go
80 lines (67 loc) · 1.8 KB
/
udpserver.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
package gokvstore
import (
"fmt"
"net"
"encoding/json"
"strings"
)
type UdpServer struct {
conn *net.UDPConn
store *Store
}
func (s *UdpServer) Init(port int, st *Store) {
var err error
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", port))
s.store = st
if err != nil {
panic(err)
}
// create the listener
s.conn, err = net.ListenUDP("udp", addr)
if err != nil {
panic(err)
}
defer s.conn.Close()
fmt.Println("UDP Server listening on port", port)
for {
// loop, listening for inbound packets
// This assumes that one packet contains one command, and clients should
// be written to assume this also
var buf = make([]byte, 1024)
n, address, err := s.conn.ReadFromUDP(buf)
if err != nil {
fmt.Println("Error: ", err)
return
}
s.handleRequest(address, string(buf[0:n]))
}
}
func (s *UdpServer) handleRequest(address *net.UDPAddr, buf string) {
var command storageCommand
err := json.Unmarshal([]byte(buf), &command)
if err != nil {
s.writeResult(address, &kvError{err.Error(), 1})
return
}
// Check the command we've been given
if strings.ToLower(command.Cmd) == "put" {
s.store.WriteItem(command.Item)
// Send back a success: true, this will always be true, pretty much
s.writeResult(address, &kvResponse{Success: true})
} else if strings.ToLower(command.Cmd) == "get" {
item, err := s.store.GetItem(command.Item)
if err != nil {
s.writeResult(address, &kvError{err.Error(), 2})
return
}
s.writeResult(address, item)
} else {
s.writeResult(address, &kvError{"Invalid command", 3})
}
}
// writeResult is a simple implementation similar to HttpServer.httpOutput
func (s *UdpServer) writeResult(address *net.UDPAddr, data interface{}) {
jsonBuf, _ := json.Marshal(data)
jsonBuf = append(jsonBuf, '\n')
s.conn.WriteToUDP(jsonBuf, address)
}