53 lines
1.1 KiB
JavaScript
53 lines
1.1 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;
|
|
|
|
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
|
|
}
|
|
socket.send(JSON.stringify(obj));
|
|
playerCount++;
|
|
} 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 = process.env.PORT || 3000;
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`Serveur WebSocket écoutant sur le port ${PORT}`);
|
|
});
|