-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeer.go
73 lines (66 loc) · 1.16 KB
/
peer.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
package main
import (
"fmt"
"io"
"log"
"net"
"github.com/tidwall/resp"
)
type Peer struct {
conn net.Conn
msgCh chan Message
delCh chan *Peer
}
func (p *Peer) Send(msg []byte) (int, error) {
return p.conn.Write(msg)
}
func NewPeer(conn net.Conn, msgCh chan Message, delCh chan *Peer) *Peer {
return &Peer{
conn: conn,
msgCh: msgCh,
delCh: delCh,
}
}
func (p *Peer) readLoop() error {
rd := resp.NewReader(p.conn)
for {
v, _, err := rd.ReadValue()
if err == io.EOF {
p.delCh <- p
break
}
if err != nil {
log.Fatal(err)
}
var cmd Command
if v.Type() == resp.Array {
rawCMD := v.Array()[0]
switch rawCMD.String() {
case CommandClient:
cmd = ClientCommand{
value: v.Array()[1].String(),
}
case CommandGET:
cmd = GetCommand{
key: v.Array()[1].Bytes(),
}
case CommandSET:
cmd = SetCommand{
key: v.Array()[1].Bytes(),
val: v.Array()[2].Bytes(),
}
case CommandHELLO:
cmd = HelloCommand{
value: v.Array()[1].String(),
}
default:
fmt.Println("got this unhandled command", rawCMD)
}
p.msgCh <- Message{
cmd: cmd,
peer: p,
}
}
}
return nil
}