Skip to content

Commit

Permalink
掉线自动重连
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Mar 5, 2020
1 parent 1d5f9d8 commit 7bd2c08
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
4 changes: 0 additions & 4 deletions src/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as colors from 'colors/safe'
import * as got from 'got'
import {Cluster} from './cluster'
import ms = require('ms')

Expand All @@ -21,9 +20,6 @@ export async function bootstrap(version: string): Promise<void> {
try {
await cluster.enable()
} catch (e) {
if (e instanceof got.HTTPError) {
console.error(e.response.body)
}
console.error(e)
process.exit(1)
}
Expand Down
41 changes: 28 additions & 13 deletions src/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ interface ICounters {

export class Cluster {
public readonly counters: ICounters = {hits: 0, bytes: 0}
public isEnabled = false

private readonly prefixUrl = process.env.CLUSTER_BMCLAPI || 'https://openbmclapi.bangbang93.com'
private readonly cacheDir = join(__dirname, '..', 'cache')
Expand Down Expand Up @@ -62,10 +63,6 @@ export class Cluster {
clusterId: this.clusterId, clusterSecret: this.clusterSecret,
},
})
this.io.on('connect', () => console.log('connected'))
this.io.on('message', (msg) => console.log(msg))
this.io.on('disconnect', () => console.log('disconnect'))
this.io.on('error', (err) => console.error(err))
}

public async getFileList(): Promise<IFileList> {
Expand Down Expand Up @@ -139,16 +136,21 @@ export class Cluster {
}

public async enable(): Promise<void> {
return new Promise((resolve, reject) => {
this.io.emit('enable', {
host: this.host,
port: this.publicPort,
version: this.version,
}, (ack) => {
if (ack !== true) return reject(ack)
resolve()
})
if (this.isEnabled) return
if (this.io.connected) {
await this._enable()
}
this.io.on('connect', async () => {
console.log('connected')
await this._enable()
this.isEnabled = true
})
this.io.on('message', (msg) => console.log(msg))
this.io.on('disconnect', () => {
console.log('disconnect')
this.isEnabled = false
})
this.io.on('error', (err) => console.error(err))
}

public async disable(): Promise<void> {
Expand Down Expand Up @@ -184,4 +186,17 @@ export class Cluster {
})
})
}

private async _enable() {
return new Promise((resolve, reject) => {
this.io.emit('enable', {
host: this.host,
port: this.publicPort,
version: this.version,
}, (ack) => {
if (ack !== true) return reject(ack)
resolve()
})
})
}
}

0 comments on commit 7bd2c08

Please sign in to comment.