-
Notifications
You must be signed in to change notification settings - Fork 1
/
socketAPI.js
67 lines (55 loc) · 1.91 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var socket_io = require('socket.io');
var io = socket_io();
var socketAPI = {};
socketAPI.io = io;
var numUsers = 0;
var usernames = [];
// Listen on every connection
io.on('connection', (socket) => {
var addedUser = false;
socket.on('add_user', (username) => {
if (addedUser) return;
// Store the username in the socket session for this client
socket.username = username;
++numUsers;
usernames.push(username);
addedUser = true;
// Client will send the "people online" message (quite redundant) and verify connected status
socket.emit('login', {
numUsers: numUsers
});
// Echo globally that a person has connected
io.sockets.emit('user_joined', {
username: socket.username,
numUsers: numUsers,
usernames: usernames
});
});
socket.on('get usernames', () => {
io.sockets.emit('user joined', {usernames: usernames});
})
// Listen on new_message (typing)
socket.on('new_message', (data) => {
// Broadcast the new message
socket.broadcast.emit('new_message', {inputToAdd : data.inputToAdd, id: data.id, username: data.username});
})
socket.on('new_position', (data) => {
// Broadcast new position
socket.broadcast.emit('new_position', {left : data.left, top : data.top, id : data.id, username: data.username})
})
// removes elem globally when a user inputs more than 3 messages
socket.on('remove_elem', (data) => {
socket.broadcast.emit('remove_elem', {idValue: data.idValue})
})
socket.on('disconnect', () => {
if (addedUser) {
--numUsers;
usernames = usernames.filter(e => e !== socket.username);
socket.broadcast.emit('user_left', {
username: socket.username,
numUsers: numUsers
});
}
});
})
module.exports = socketAPI;