GrandTabernacleAutoVI/server/server.js

92 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-11-14 17:45:09 +01:00
const express = require('express');
const http = require('http');
2023-11-14 17:35:47 +01:00
const WebSocket = require('ws');
2023-11-14 17:45:09 +01:00
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
2023-11-14 17:35:47 +01:00
2023-11-14 17:45:09 +01:00
const connections = new Set();
2023-11-14 17:35:47 +01:00
var playerCount = 0;
2023-11-18 13:38:29 +01:00
var players = []
2023-11-14 17:35:47 +01:00
2023-11-14 17:45:09 +01:00
app.get('/', (req, res) => {
2023-11-14 18:07:51 +01:00
res.send('Grand Tabernacle Auto VI');
2023-11-14 17:45:09 +01:00
});
2023-11-19 18:23:15 +01:00
players.push({
id: playerCount,
2023-11-19 18:38:27 +01:00
x: 100,
y: 100,
dir: 4,
visibleDir: 4,
2023-11-19 18:23:15 +01:00
name: playerCount.toString() + "joueur"
})
playerCount++;
2023-11-18 20:17:47 +01:00
function createNewPlayer(socket){
var obj = {
id: playerCount,
2023-11-19 18:55:21 +01:00
x: Math.floor(Math.random()*1000),
y: Math.floor(Math.random()*1000),
2023-11-19 18:23:15 +01:00
dir: 0,
visibleDir: 0,
2023-11-18 20:17:47 +01:00
name: playerCount.toString() + "joueur"
}
2023-11-19 18:23:15 +01:00
players.push(obj);
playerCount++;
2023-11-18 20:17:47 +01:00
socket.send(JSON.stringify({
type: "connect",
data: {
playerId: obj.id,
players: players
}
}))
broadcast(JSON.stringify({
type: "newplayer",
data: obj
}), obj.id);
socket.id = obj.id;
2023-11-14 17:45:09 +01:00
connections.add(socket);
2023-11-18 20:17:47 +01:00
}
wss.on('connection', (socket) => {
//create new player, send informations to new player and broadcast new player for all
createNewPlayer(socket);
2023-11-14 17:45:09 +01:00
socket.on('message', (message) => {
message = JSON.parse(message);
2023-11-18 20:17:47 +01:00
if (message.type == "ping") {
2023-11-14 17:45:09 +01:00
socket.send("pong");
2023-11-18 20:17:47 +01:00
} else if(message.type=="update") {
broadcast(JSON.stringify(message), socket.id);
2023-11-14 17:45:09 +01:00
}
});
2023-11-14 17:35:47 +01:00
socket.on('close', () => {
2023-11-18 20:17:47 +01:00
for (var i = players.length - 1; i >= 0; i--) {
if(players[i].id==socket.id){
players.splice(i, 1);
}
}
2023-11-14 17:35:47 +01:00
connections.delete(socket);
});
});
2023-11-18 20:17:47 +01:00
function broadcast(message, exceptId = -1) {
2023-11-14 17:45:09 +01:00
connections.forEach((socket) => {
2023-11-18 20:17:47 +01:00
if (socket.readyState === WebSocket.OPEN && socket.id!=exceptId) {
2023-11-14 17:45:09 +01:00
socket.send(message);
}
});
2023-11-14 17:35:47 +01:00
}
2023-11-14 17:45:09 +01:00
2023-11-20 11:01:11 +01:00
const PORT = 8080;
2023-11-14 17:45:09 +01:00
server.listen(PORT, () => {
console.log(`Serveur WebSocket écoutant sur le port ${PORT}`);
});