Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make webserver stoppable once created #198

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions src/webserver.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { Bot } from 'mineflayer'
import { BotStateMachine, StateBehavior } from './statemachine'
import socketLoader, { Socket } from 'socket.io'
import { Server as SocketServer, Socket } from 'socket.io'
import path from 'path'
import express from 'express'
import httpLoader from 'http'
import { globalSettings } from '.'

const publicFolder = './../web'

// TODO Add option to shutdown server

/**
* A web server which allows users to view the current state of the
* bot behavior state machine.
*/
export class StateMachineWebserver {
private serverRunning: boolean = false
private http: httpLoader.Server | undefined
private io: SocketServer | undefined

readonly bot: Bot
readonly stateMachine: BotStateMachine
Expand Down Expand Up @@ -54,14 +54,25 @@ export class StateMachineWebserver {
app.use('/web', express.static(path.join(__dirname, publicFolder)))
app.get('/', (req, res) => res.sendFile(path.join(__dirname, publicFolder, 'index.html')))

const http = httpLoader.createServer(app)
this.http = httpLoader.createServer(app)
this.io = new SocketServer(this.http)

this.io.on('connection', (socket: Socket) => this.onConnected(socket))

this.http.listen(this.port, () => this.onStarted())
}

// @ts-expect-error ; Why? Not sure. Probably a type-def loading issue. Either way, it's safe.
const io = socketLoader(http)
/**
* Stops the web server.
*/
stopServer (): void {
this.serverRunning = false

io.on('connection', (socket: Socket) => this.onConnected(socket))
this.io?.close()
this.http?.close()

http.listen(this.port, () => this.onStarted())
this.io = undefined
this.http = undefined
}

/**
Expand Down
Loading