-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketapi.js
43 lines (35 loc) · 1.09 KB
/
socketapi.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
const io = require("socket.io")();
const socketapi = {
io: io
};
let namearr = [];
let ids = [];
// Add your socket.io logic here!
io.on("connection", function (socket) {
io.emit('onlineUsers', namearr)
socket.on('disconnect', () => {
let index = ids.indexOf(socket.id);
let dname = namearr[index];
socket.broadcast.emit('left', dname);
namearr.splice(index, 1);
ids.splice(index, 1);
io.emit('onlineUsers', namearr);
})
socket.on('newUser', (username) => {
namearr.push(username);
ids.push(socket.id);
io.emit('onlineUsers', namearr);
socket.broadcast.emit('joined', username);
})
socket.on('newMessage', (data) => {
let index = ids.indexOf(socket.id);
let user = namearr[index];
io.emit('newMessage', { data: data.message, user, clientId: data.clientSocketId });
});
socket.on('typing', () => {
let index = ids.indexOf(socket.id);
let user = namearr[index];
socket.broadcast.emit('typing', { user });
});
});
module.exports = socketapi;