Skip to content

Commit cc4b24e

Browse files
committed
p2p: move ping handling into pingLoop goroutine
1 parent a56b89a commit cc4b24e

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

p2p/peer.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ type Peer struct {
110110
wg sync.WaitGroup
111111
protoErr chan error
112112
closed chan struct{}
113+
pingRecv chan struct{}
113114
disc chan DiscReason
114115

115116
// events receives message send / receive events if set
@@ -231,6 +232,7 @@ func newPeer(log log.Logger, conn *conn, protocols []Protocol) *Peer {
231232
disc: make(chan DiscReason),
232233
protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
233234
closed: make(chan struct{}),
235+
pingRecv: make(chan struct{}, 16),
234236
log: log.New("id", conn.node.ID(), "conn", conn.flags),
235237
}
236238
return p
@@ -291,9 +293,11 @@ loop:
291293
}
292294

293295
func (p *Peer) pingLoop() {
294-
ping := time.NewTimer(pingInterval)
295296
defer p.wg.Done()
297+
298+
ping := time.NewTimer(pingInterval)
296299
defer ping.Stop()
300+
297301
for {
298302
select {
299303
case <-ping.C:
@@ -302,6 +306,9 @@ func (p *Peer) pingLoop() {
302306
return
303307
}
304308
ping.Reset(pingInterval)
309+
case <-p.pingRecv:
310+
SendItems(p.rw, pongMsg)
311+
305312
case <-p.closed:
306313
return
307314
}
@@ -328,7 +335,10 @@ func (p *Peer) handle(msg Msg) error {
328335
switch {
329336
case msg.Code == pingMsg:
330337
msg.Discard()
331-
go SendItems(p.rw, pongMsg)
338+
select {
339+
case p.pingRecv <- struct{}{}:
340+
case <-p.closed:
341+
}
332342
case msg.Code == discMsg:
333343
// This is the last message. We don't need to discard or
334344
// check errors because, the connection will be closed after it.

0 commit comments

Comments
 (0)