79 lines
1.7 KiB
JavaScript
79 lines
1.7 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');
|
|
});
|
|
|
|
function createNewPlayer(socket){
|
|
var obj = {
|
|
id: playerCount,
|
|
x: 0,
|
|
y: 0,
|
|
name: playerCount.toString() + "joueur"
|
|
}
|
|
|
|
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;
|
|
connections.add(socket);
|
|
players.push(obj);
|
|
playerCount++;
|
|
}
|
|
|
|
wss.on('connection', (socket) => {
|
|
//create new player, send informations to new player and broadcast new player for all
|
|
createNewPlayer(socket);
|
|
|
|
socket.on('message', (message) => {
|
|
message = JSON.parse(message);
|
|
if (message.type == "ping") {
|
|
socket.send("pong");
|
|
} else if(message.type=="update") {
|
|
broadcast(JSON.stringify(message), socket.id);
|
|
}
|
|
});
|
|
|
|
socket.on('close', () => {
|
|
for (var i = players.length - 1; i >= 0; i--) {
|
|
if(players[i].id==socket.id){
|
|
players.splice(i, 1);
|
|
}
|
|
}
|
|
connections.delete(socket);
|
|
});
|
|
});
|
|
|
|
function broadcast(message, exceptId = -1) {
|
|
connections.forEach((socket) => {
|
|
if (socket.readyState === WebSocket.OPEN && socket.id!=exceptId) {
|
|
socket.send(message);
|
|
}
|
|
});
|
|
}
|
|
|
|
const PORT = 9600;
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`Serveur WebSocket écoutant sur le port ${PORT}`);
|
|
});
|