2020-09-09 15:41:05 +00:00
|
|
|
import http from 'http'
|
2022-01-13 17:02:55 +00:00
|
|
|
import https from 'https'
|
2020-09-09 15:41:05 +00:00
|
|
|
|
|
|
|
export default class HttpServer {
|
2020-09-13 04:36:33 +00:00
|
|
|
constructor(config) {
|
2022-01-13 17:02:55 +00:00
|
|
|
this.ishttps = false
|
|
|
|
this.active = null
|
|
|
|
this.sockets = new Set()
|
|
|
|
this.creator = http
|
|
|
|
if (config && config.https) {
|
|
|
|
this.creator = https
|
|
|
|
this.ishttps = true
|
2020-09-09 15:41:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
createServer(opts, listener) {
|
2022-01-13 17:02:55 +00:00
|
|
|
let server = this.creator.createServer(opts, listener)
|
2020-09-09 15:41:05 +00:00
|
|
|
|
|
|
|
server.on('connection', (socket) => {
|
2022-01-13 17:02:55 +00:00
|
|
|
this.sockets.add(socket)
|
2020-09-09 15:41:05 +00:00
|
|
|
|
|
|
|
socket.once('close', () => {
|
2022-01-13 17:02:55 +00:00
|
|
|
this.sockets.delete(socket)
|
2020-09-09 15:41:05 +00:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2022-02-04 09:33:03 +00:00
|
|
|
server.listenAsync = (port, host) => {
|
|
|
|
return new Promise((res, rej) => {
|
|
|
|
server.once('error', rej)
|
|
|
|
|
|
|
|
server.listen(port, host || '0.0.0.0', () => {
|
|
|
|
server.off('error', rej)
|
|
|
|
res()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-01-13 17:02:55 +00:00
|
|
|
this.active = server
|
2020-09-09 15:41:05 +00:00
|
|
|
return server
|
|
|
|
}
|
|
|
|
|
2022-01-13 17:02:55 +00:00
|
|
|
closeServer() {
|
|
|
|
if (!this.active) return Promise.resolve()
|
2020-09-09 15:41:05 +00:00
|
|
|
|
2022-01-13 17:02:55 +00:00
|
|
|
return new Promise((res, rej) => {
|
|
|
|
this.sockets.forEach(function(socket) {
|
|
|
|
socket.destroy()
|
2020-09-09 15:41:05 +00:00
|
|
|
})
|
2022-01-13 17:02:55 +00:00
|
|
|
this.sockets.clear()
|
2020-09-09 15:41:05 +00:00
|
|
|
|
2022-01-13 17:02:55 +00:00
|
|
|
this.active.close(err => {
|
2022-02-04 09:33:03 +00:00
|
|
|
if (err) {
|
|
|
|
if (err.code !== 'ERR_SERVER_NOT_RUNNING') return rej(err)
|
|
|
|
}
|
2022-01-13 17:02:55 +00:00
|
|
|
this.active = null
|
|
|
|
|
|
|
|
// Waiting 1 second for it to close down
|
2022-02-04 09:33:03 +00:00
|
|
|
setTimeout(function() {res() }, 100)
|
2022-01-13 17:02:55 +00:00
|
|
|
})
|
|
|
|
})
|
2020-09-09 15:41:05 +00:00
|
|
|
}
|
|
|
|
}
|