GrandTabernacleAutoVI/server/server.js
2023-11-18 13:38:29 +01:00

70 lines
1.4 KiB
JavaScript

const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const connections = new Set();
var playerCount = 0;
var players = []
app.get('/', (req, res) => {
res.send('Grand Tabernacle Auto VI');
});
wss.on('connection', (socket) => {
connections.add(socket);
socket.on('message', (message) => {
message = JSON.parse(message);
if (message.type == "connect") {
var obj = {
id: playerCount,
x: 0,
y: 0,
name: playerCount.toString() + "joueur"
}
players.push(obj)
playerCount++;
socket.send(JSON.stringify({
type: "connect",
data: {
playerId: obj.id,
players: players
}
}))
broadcast(JSON.stringify({
type: "newplayer",
data: obj
}));
} else if (message.type == "ping") {
socket.send("pong");
} else {
broadcast(JSON.stringify(message));
}
});
socket.on('close', () => {
connections.delete(socket);
});
});
function broadcast(message) {
connections.forEach((socket) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(message);
}
});
}
const PORT = 9600;
server.listen(PORT, () => {
console.log(`Serveur WebSocket écoutant sur le port ${PORT}`);
});