Close the websocket only when no one is using it

This commit is contained in:
Yoann Ciabaud 2016-03-14 16:29:51 +01:00 committed by Feross Aboukhadijeh
parent c2115fbf7f
commit 35e6eeaef2
2 changed files with 15 additions and 6 deletions

View File

@ -88,7 +88,7 @@ WebSocketTracker.prototype.destroy = function (cb) {
self.destroyed = true
clearInterval(self.interval)
delete socketPool[self.announceUrl]
if (socketPool[self.announceUrl]) socketPool[self.announceUrl].consumers--
self.socket.removeListener('connect', self._onSocketConnectBound)
self.socket.removeListener('data', self._onSocketDataBound)
@ -100,11 +100,16 @@ WebSocketTracker.prototype.destroy = function (cb) {
self._onSocketDataBound = null
self._onSocketCloseBound = null
self.socket.on('error', noop) // ignore all future errors
try {
self.socket.destroy(cb)
} catch (err) {
cb(null)
if (socketPool[self.announceUrl].consumers === 0) {
delete socketPool[self.announceUrl]
self.socket.on('error', noop) // ignore all future errors
try {
self.socket.destroy(cb)
} catch (err) {
if (cb) cb()
}
}
self.socket = null
@ -122,7 +127,10 @@ WebSocketTracker.prototype._openSocket = function () {
self.socket = socketPool[self.announceUrl]
if (!self.socket) {
self.socket = socketPool[self.announceUrl] = new Socket(self.announceUrl)
self.socket.consumers = 1
self.socket.on('connect', self._onSocketConnectBound)
} else {
socketPool[self.announceUrl].consumers++
}
self.socket.on('data', self._onSocketDataBound)

View File

@ -599,6 +599,7 @@ Server.prototype._onWebSocketClose = function (socket) {
var swarm = self.torrents[infoHash]
if (swarm) {
swarm.announce({
type: 'ws',
event: 'stopped',
numwant: 0,
peer_id: socket.peerId