-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
86 lines (74 loc) · 2.94 KB
/
server.js
File metadata and controls
86 lines (74 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const express = require("express");
const Docker = require("dockerode");
const WebSocket = require("ws");
const app = express();
const docker = new Docker();
const wss = new WebSocket.Server({ port: 3001 });
const GAME_IMAGE = "my-pixel-streaming-game";
const CONTAINERS = {};
let playerCount = 0;
// Функция запуска контейнера
async function startContainer(name, port) {
try {
const container = await docker.createContainer({
Image: GAME_IMAGE,
name,
Tty: true,
ExposedPorts: { "8888/tcp": {} },
HostConfig: {
PortBindings: { "8888/tcp": [{ HostPort: port.toString() }] },
NetworkMode: "nat",
},
Cmd: ["cmd", "/c", "C:\\GameServer\\Start_Games.bat"],
});
await container.start();
CONTAINERS[name] = container;
console.log(`✅ Запущен контейнер ${name} на порту ${port}`);
} catch (error) {
console.error(`Ошибка запуска контейнера ${name}:`, error);
}
}
// Функция остановки контейнера
async function stopContainer(name) {
if (CONTAINERS[name]) {
try {
await CONTAINERS[name].stop();
await CONTAINERS[name].remove();
delete CONTAINERS[name];
console.log(`🛑 Остановлен контейнер ${name}`);
} catch (error) {
console.error(`Ошибка остановки контейнера ${name}:`, error);
}
}
}
// API-запрос для запуска контейнера вручную
app.post("/start/:id", async (req, res) => {
const id = req.params.id;
await startContainer(`game_${id}`, 8000 + parseInt(id));
res.send(`Контейнер game_${id} запущен.`);
});
// API-запрос для остановки контейнера вручную
app.post("/stop/:id", async (req, res) => {
const id = req.params.id;
await stopContainer(`game_${id}`);
res.send(`Контейнер game_${id} остановлен.`);
});
// WebSocket сервер для отслеживания игроков
wss.on("connection", (ws) => {
console.log("📡 Игрок подключился");
playerCount++;
// Запускаем новый сервер при необходимости
if (playerCount > Object.keys(CONTAINERS).length) {
startContainer(`game_${playerCount}`, 8000 + playerCount);
}
ws.on("close", () => {
console.log("🚪 Игрок отключился");
playerCount--;
// Останавливаем сервер, если игроков нет
if (playerCount < Object.keys(CONTAINERS).length) {
stopContainer(`game_${playerCount + 1}`);
}
});
});
// Запуск API сервера
app.listen(3000, () => console.log("🚀 API сервер запущен на порту 3000"));