silphius/app/websocket.js
2024-06-12 23:17:24 -05:00

46 lines
1.0 KiB
JavaScript

import {WebSocketServer} from 'ws';
import Engine from '@/engine/engine.js';
import Server from '@/net/server/server.js';
const wss = new WebSocketServer({
noServer: true,
});
function onUpgrade(request, socket, head) {
const {pathname} = new URL(request.url, 'wss://base.url');
if (pathname === '/ws') {
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request);
});
}
else {
socket.destroy();
}
}
export default async function listen(server) {
server.on('upgrade', onUpgrade);
class SocketServer extends Server {
transmit(ws, packed) { ws.send(packed); }
}
const engine = new Engine(SocketServer);
await engine.load();
engine.start();
async function onConnect(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);
}