forked from yangl1996/synclc-sim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.go
74 lines (66 loc) · 1.04 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 (
"net"
"encoding/gob"
"log"
)
type Message interface{}
type peerConn struct {
net.Conn
*gob.Encoder
*gob.Decoder
}
func (p *peerConn) sendData(from chan Message) error {
for m := range from {
err := p.Encode(&m)
if err != nil {
return err
}
}
return nil
}
func (p *peerConn) receiveData(to chan peerMessage, idx int) error {
for {
var msg Message
err := p.Decode(&msg)
if err != nil {
return err
}
to <- peerMessage{msg, idx}
}
}
type peer struct {
index int
hpConn *peerConn
lpConn *peerConn
inCh chan peerMessage
hpCh chan Message
lpCh chan Message
}
func (p *peer) handle() {
go func() {
err := p.hpConn.sendData(p.hpCh)
if err != nil {
log.Fatalln(err)
}
}()
go func() {
err := p.lpConn.sendData(p.lpCh)
if err != nil {
log.Fatalln(err)
}
}()
go func() {
err := p.hpConn.receiveData(p.inCh, p.index)
if err != nil {
log.Fatalln(err)
}
}()
go func() {
err := p.lpConn.receiveData(p.inCh, p.index)
if err != nil {
log.Fatalln(err)
}
}()
select{}
}