Files
cactoz.su/frontend/js/game/network.js
T
cacto 864868de49 Лобби: комнаты на сервере (C++) и UI на клиенте
Сервер: Lobby/Room/Player — create/join/leave/list_rooms, broadcast обновлений,
проверка авторизации (hello) и состояния комнаты (waiting/full/in_progress).
Клиент: полноценный UI лобби (создание, список, вход в комнату, выход),
блокировка кнопок до установки WS-соединения.
nginx: no-cache для JS/CSS (нет хеширования имён файлов).
2026-07-26 21:22:20 +05:00

51 lines
1.2 KiB
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);
}
createRoom(mode) {
this.send(ClientMessage.LOBBY_CREATE_ROOM, { mode });
}
joinRoom(roomId) {
this.send(ClientMessage.LOBBY_JOIN_ROOM, { room_id: roomId });
}
leaveRoom() {
this.send(ClientMessage.LOBBY_LEAVE_ROOM);
}
}
export { ServerMessage };