Frontend — чистый HTML/CSS/JS без сборки (резюме, проекты, игра-заглушки). Gameserver — C++ на uWebSockets (CMake FetchContent), протокол hello/lobby.list_rooms/error проверен end-to-end.
39 lines
958 B
JavaScript
39 lines
958 B
JavaScript
import { ClientMessage, ServerMessage } from './protocol.js';
|
|
|
|
export class Network {
|
|
constructor() {
|
|
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
|
this.socket = new WebSocket(`${proto}://${location.host}/ws`);
|
|
this.handlers = new Map();
|
|
|
|
this.socket.addEventListener('open', () => this._emit('_open'));
|
|
this.socket.addEventListener('close', () => this._emit('_close'));
|
|
this.socket.addEventListener('message', (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
this._emit(msg.type, msg.payload);
|
|
});
|
|
}
|
|
|
|
on(type, handler) {
|
|
this.handlers.set(type, handler);
|
|
}
|
|
|
|
_emit(type, payload) {
|
|
this.handlers.get(type)?.(payload);
|
|
}
|
|
|
|
send(type, payload = {}) {
|
|
this.socket.send(JSON.stringify({ type, payload }));
|
|
}
|
|
|
|
hello(nickname) {
|
|
this.send(ClientMessage.HELLO, { nickname });
|
|
}
|
|
|
|
listRooms() {
|
|
this.send(ClientMessage.LOBBY_LIST_ROOMS);
|
|
}
|
|
}
|
|
|
|
export { ServerMessage };
|