Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
Join after swarm is listening
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffpeterson committed Nov 13, 2019
1 parent 7647274 commit cb901b5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 18 deletions.
37 changes: 19 additions & 18 deletions src/Network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import PeerConnection from './PeerConnection'
export default class Network {
selfId: PeerId
joined: Set<DiscoveryId>
pending: Set<DiscoveryId>
peers: Map<PeerId, NetworkPeer>
peerQ: Queue<NetworkPeer>
swarm?: Swarm
Expand All @@ -16,30 +15,21 @@ export default class Network {
constructor(selfId: PeerId) {
this.selfId = selfId
this.joined = new Set()
this.pending = new Set()
this.peers = new Map()
this.peerQ = new Queue('Network:peerQ')
this.joinOptions = { announce: true, lookup: true }
}

join(discoveryId: DiscoveryId): void {
if (this.swarm) {
if (this.joined.has(discoveryId)) return

this.joined.add(discoveryId)
this.swarm.join(decodeId(discoveryId), this.joinOptions)
this.pending.delete(discoveryId)
} else {
this.pending.add(discoveryId)
}
if (this.joined.has(discoveryId)) return
this.joined.add(discoveryId)
this.swarmJoin(discoveryId)
}

leave(discoveryId: DiscoveryId): void {
this.pending.delete(discoveryId)
if (!this.joined.has(discoveryId)) return

if (this.swarm) this.swarm.leave(decodeId(discoveryId))
this.joined.delete(discoveryId)
this.swarmLeave(discoveryId)
}

setSwarm(swarm: Swarm, joinOptions?: JoinOptions): void {
Expand All @@ -48,10 +38,7 @@ export default class Network {
if (joinOptions) this.joinOptions = joinOptions
this.swarm = swarm
this.swarm.on('connection', this.onConnection)

for (const discoveryId of this.pending) {
this.join(discoveryId)
}
this.swarm.on('listening', this.onListening)
}

get closedConnectionCount(): number {
Expand Down Expand Up @@ -84,6 +71,20 @@ export default class Network {
})
}

private swarmJoin(discoveryId: DiscoveryId): void {
if (this.swarm) this.swarm.join(decodeId(discoveryId), this.joinOptions)
}

private swarmLeave(discoveryId: DiscoveryId): void {
if (this.swarm) this.swarm.leave(decodeId(discoveryId))
}

private onListening = () => {
for (const discoveryId of this.joined) {
this.swarmJoin(discoveryId)
}
}

private onConnection = async (socket: Socket, details: ConnectionDetails) => {
details.reconnect(false)

Expand Down
1 change: 1 addition & 0 deletions src/SwarmInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export interface SwarmEvents {
disconnection(socket: Socket, details: ConnectionDetails): void
peer(peer: PeerInfo): void
updated(info: { key: Buffer }): void
listening(): void
}

export interface JoinOptions {
Expand Down

0 comments on commit cb901b5

Please sign in to comment.