Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions p2p/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ type Peer struct {
wg sync.WaitGroup
protoErr chan error
closed chan struct{}
pingRecv chan struct{}
disc chan DiscReason

// events receives message send / receive events if set
Expand Down Expand Up @@ -185,6 +186,7 @@ func newPeer(conn *conn, protocols []Protocol) *Peer {
disc: make(chan DiscReason),
protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
closed: make(chan struct{}),
pingRecv: make(chan struct{}, 16),
log: log.New("id", conn.node.ID(), "conn", conn.flags),
}
return p
Expand All @@ -201,8 +203,9 @@ func (p *Peer) run() (remoteRequested bool, err error) {
readErr = make(chan error, 1)
reason DiscReason // sent to the peer
)
p.wg.Add(1)
p.wg.Add(2)
go p.readLoop(readErr)
go p.pingLoop()

// Start all protocol handlers.
writeStart <- struct{}{}
Expand Down Expand Up @@ -244,9 +247,11 @@ loop:
}

func (p *Peer) pingLoop() {
ping := time.NewTimer(pingInterval)
defer p.wg.Done()

ping := time.NewTimer(pingInterval)
defer ping.Stop()

for {
select {
case <-ping.C:
Expand All @@ -255,6 +260,10 @@ func (p *Peer) pingLoop() {
return
}
ping.Reset(pingInterval)

case <-p.pingRecv:
SendItems(p.rw, pongMsg)

case <-p.closed:
return
}
Expand All @@ -281,7 +290,10 @@ func (p *Peer) handle(msg Msg) error {
switch {
case msg.Code == pingMsg:
msg.Discard()
go SendItems(p.rw, pongMsg)
select {
case p.pingRecv <- struct{}{}:
case <-p.closed:
}
case msg.Code == discMsg:
var reason [1]DiscReason
// This is the last message. We don't need to discard or
Expand Down
Loading