refactor: tidy

This commit is contained in:
cha0s 2024-06-13 21:00:40 -05:00
parent e9da3871a4
commit c1758ef3d6

View File

@ -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) { export default async function listen(server) {
server.on('upgrade', onUpgrade); 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));
});
}
} }