Files
cactoz.su/frontend/js/game/network.js
T
cacto a9d2a6b15c Каркас проекта: ТЗ, nginx+gameserver(uWebSockets) в Docker, /ws echo
Frontend — чистый HTML/CSS/JS без сборки (резюме, проекты, игра-заглушки).
Gameserver — C++ на uWebSockets (CMake FetchContent), протокол hello/lobby.list_rooms/error проверен end-to-end.
2026-07-26 19:31:44 +05:00

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 };