Skip to content
This repository has been archived by the owner on Aug 23, 2019. It is now read-only.

fix: add start method #69

Merged
merged 2 commits into from
Apr 23, 2018
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ p.on('ping', function (time) {
console.log(time + 'ms')
p.stop() // stop sending pings
})

p.start()
```
41 changes: 22 additions & 19 deletions src/ping.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,21 @@ class Ping extends EventEmitter {
constructor (swarm, peer) {
super()

let stop = false
let shake
let self = this
this._stopped = false
this.peer = peer
this.swarm = swarm
}

log('dialing %s to %s', PROTOCOL, peer.id.toB58String())
start () {
log('dialing %s to %s', PROTOCOL, this.peer.id.toB58String())

swarm.dial(peer, PROTOCOL, (err, conn) => {
this.swarm.dial(this.peer, PROTOCOL, (err, conn) => {
if (err) {
return this.emit('error', err)
}

const stream = handshake({ timeout: 0 })
shake = stream.handshake
this.shake = stream.handshake

pull(
stream,
Expand All @@ -38,11 +40,12 @@ class Ping extends EventEmitter {
)

// write and wait to see ping back
const self = this
function next () {
let start = new Date()
let buf = rnd(PING_LENGTH)
shake.write(buf)
shake.read(PING_LENGTH, (err, bufBack) => {
self.shake.write(buf)
self.shake.read(PING_LENGTH, (err, bufBack) => {
let end = new Date()
if (err || !buf.equals(bufBack)) {
const err = new Error('Received wrong ping ack')
Expand All @@ -51,7 +54,7 @@ class Ping extends EventEmitter {

self.emit('ping', end - start)

if (stop) {
if (self._stopped) {
return
}
next()
Expand All @@ -60,19 +63,19 @@ class Ping extends EventEmitter {

next()
})
}

this.stop = () => {
if (stop || !shake) {
return
}
stop () {
if (this._stopped || !this.shake) {
return
}

stop = true
this._stopped = true

pull(
pull.empty(),
shake.rest()
)
}
pull(
pull.empty(),
this.shake.rest()
)
}
}

Expand Down
6 changes: 6 additions & 0 deletions test/test-ping.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ describe('libp2p ping', () => {
p.stop()
done()
})

p.start()
})

it('ping 5 times from peerB to peerA', (done) => {
Expand All @@ -90,6 +92,8 @@ describe('libp2p ping', () => {
done()
}
})

p.start()
})

it('ping itself', (done) => {
Expand All @@ -104,6 +108,8 @@ describe('libp2p ping', () => {
p.stop()
done()
})

p.start()
})

it('unmount PING protocol', () => {
Expand Down