-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
75 lines (67 loc) · 2.34 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const { Socket } = require('engine.io');
const express = require('express');
const http = require('http');
const app = express();
const server = http.Server(app);
const io = require('socket.io')(server);
const hostname = '127.0.0.1';
const port = 8080;
let socketClients = [];
let messages = [];
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile('index.html', { root: __dirname });
})
// communication entre les clients et le serveur
io.on('connection', (socket) => {
console.dir(socket.id);
socketClients.push({ id: socket.id })
socket.emit("init", {
message: "Bienvenue nouveau client",
id: socket.id,
socketClients: socketClients,
messages:messages
})
socket.on('initResponse', (initResponse) => {
socketClients = initResponse.socketClients;
console.dir(socketClients);
// partager aux clients déjà connectés
socket.broadcast.emit('newClient',{socketClients:socketClients})
})
socket.on('newMessage',(newMessage)=>{
messages = newMessage.messages;
console.dir(messages)
// je partage en broadcast le tableau message
socket.broadcast.emit('newMessageResponse',{messages:messages})
})
socket.on("newPrivateMessage", (newPrivateMessage)=>{
// je reçois idContact, id, message, pseudo, date
// je dois faire un emit sur un unique id (newPrivateMessage.idContact)
console.dir(newPrivateMessage)
// stockage des messages éventuels
socket.broadcast.to(newPrivateMessage.idContact).emit("newPrivateMessageResponse",{
newPrivateMessageResponse:newPrivateMessage
})
})
if (socketClients.length > 0) {
socket.on('disconnect', () => {
// socket.id = client déconnecté
for (
let i = 0;
i < socketClients.length;
i++) {
if (socketClients[i].id === socket.id) {
socketClients.splice(i, 1);
}
}
console.log(socket.id);
console.dir(socketClients);
socket.broadcast.emit('clientDisconnect', {
socketClients: socketClients
})
})
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});