diff --git a/app/websocket.js b/app/websocket.js index 60a4ca0..795ade8 100644 --- a/app/websocket.js +++ b/app/websocket.js @@ -19,45 +19,53 @@ function onUpgrade(request, socket, head) { } } +let engine; +let onConnect; + +function createOnConnect(engine) { + onConnect = async (ws) => { + ws.on('close', () => { + engine.disconnectPlayer(ws); + }) + ws.on('message', (packed) => { + engine.server.accept(ws, new DataView(packed.buffer, packed.byteOffset, packed.length)); + }); + await engine.connectPlayer(ws); + }; + wss.on('connection', onConnect); +} + +class SocketServer extends Server { + transmit(ws, packed) { ws.send(packed); } +} + +async function createEngine(Engine) { + engine = new Engine(SocketServer); + await engine.load(); + engine.start(); + return engine; +} + +async function remakeServer(Engine) { + if (onConnect) { + wss.off('connection', onConnect); + } + if (engine) { + for (const [connection] of engine.connectedPlayers) { + connection.close(); + } + } + createOnConnect(await createEngine(Engine)); +} + +await remakeServer(Engine); + +if (import.meta.hot) { + import.meta.hot.accept('./engine/engine.js', async ({default: Engine}) => { + await remakeServer(Engine); + }); +} + export default async function listen(server) { server.on('upgrade', onUpgrade); - - class SocketServer extends Server { - transmit(ws, packed) { ws.send(packed); } - } - - let onConnect; - function makeOnConnect(engine) { - return async (ws) => { - ws.on('close', () => { - engine.disconnectPlayer(ws); - }) - ws.on('message', (packed) => { - engine.server.accept(ws, new DataView(packed.buffer, packed.byteOffset, packed.length)); - }); - await engine.connectPlayer(ws); - }; - } - - let engine; - async function makeEngine(Engine) { - const engine = new Engine(SocketServer); - await engine.load(); - engine.start(); - return engine; - } - - engine = await makeEngine(Engine); - wss.on('connection', onConnect = makeOnConnect(engine)); - - if (import.meta.hot) { - import.meta.hot.accept('./engine/engine.js', async ({default: Engine}) => { - wss.off('connection', onConnect); - for (const [connection] of engine.connectedPlayers) { - connection.close(); - } - engine = await makeEngine(Engine); - wss.on('connection', onConnect = makeOnConnect(engine)); - }); - } }