扩展实现
- https://github.com/webtorrent/lt_donthave/blob/master/index.js
import arrayRemove from 'unordered-array-remove'
import {
EventEmitter } from 'events'
import debugFactory from 'debug'
const debug = debugFactory('lt_donthave')
export default () => {
class ltDontHave extends EventEmitter {
constructor (wire) {
super()
this._peerSupports = false
this._wire = wire
}
onExtendedHandshake () {
this._peerSupports = true
}
onMessage (buf) {
let index
try {
const view = new DataView(buf.buffer)
index = view.getUint32(0)
} catch (err) {
return
}
if (!this._wire.peerPieces.get(index)) return
debug('got donthave %d', index)
this._wire.peerPieces.set(index, false)
this.emit('donthave', index)
this._failRequests(index)
}
donthave (index) {
if (!this._peerSupports) return
debug('donthave %d', index)
const buf = new Uint8Array(4)
const view = new DataView(buf.buffer)
view.setUint32(0, index)
console.log(">>>>>>>>>>>>>>>>", index, ">>>>>>>>>>>>>>", buf)
this._wire.extended('lt_donthave', buf)
}
_failRequests (index) {
const requests = this._wire.requests
for (let i = 0; i < requests.length; i++) {
const req = requests[i]
if (req.piece === index) {
arrayRemove(requests, i)
i -= 1
this._wire._callback(req, new Error('peer sent donthave'), null)
}
}
}
}
ltDontHave.prototype.name = 'lt_donthave'
return ltDontHave
}
测试代码
import fixtures from 'webtorrent-fixtures'
import Protocol from 'bittorrent-protocol'
import test from 'tape'
import ltDontHave from './index.js'
const {
leaves } = fixtures
const id1 = Buffer.from('01234567890123456789')
const id2 = Buffer.from('12345678901234567890')
const wire1 = new