GrandTabernacleAutoVI/server/server.js
killianmarty 02cc1ed028 server
2023-11-14 17:35:47 +01:00

40 lines
962 B
JavaScript

// server.js
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });
const connections = new Set();
var playerCount = 0;
server.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
}
socket.send(JSON.stringify(obj));
playerCount++;
}else if(message.type == "ping"){
socket.send("pong");
}else{
broadcast(JSON.stringify(message));
}
});
// Écoute des déconnexions du client
socket.on('close', () => {
connections.delete(socket);
});
});
function broadcast(message) {
connections.forEach((socket) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(message);
}
});
}