-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
76 lines (57 loc) · 1.71 KB
/
index.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
76
// Import express and create instance
const express = require('express');
const app = express();
// Create Instance of http server
const http = require('http').Server(app);
const port = 8080; // Port to use for server
const io = require('socket.io')(http);
app.use('/', express.static('public'))
// List of active Users
const users = {};
const idToUsers = {};
// List of avail Rooms
const rooms = ['LOBBY'];
io.on('connection', (socket) => {
socket.emit('connected');
socket.on("login", username => {
if (!users[username]) {
let userData = {};
userData['socketID'] = socket.id;
userData['roomID'] = 'LOBBY';
users[username] = userData
idToUsers[socket.id] = username;
socket.join('LOBBY');
socket.emit("ROOMS", rooms);
} else {
socket.emit("userInUse");
}
});
socket.on("Change Room", room => {
if(!rooms.includes(room)) {
rooms.push(room);
io.emit("ROOMS", rooms);
}
let userName = idToUsers[socket.id];
let userData = users[userName];
socket.leave(userData['roomID']);
socket.join(room);
userData['roomID'] = room;
users[userName] = userData;
});
socket.on("MessageToServer", msg => {
let dataPacket = {};
dataPacket['fromUser'] = idToUsers[socket.id];
dataPacket['msg'] = msg;
let userName = idToUsers[socket.id];
let userData = users[userName];
socket.broadcast.to(userData['roomID']).emit("MessageFromServer", dataPacket);
});
socket.on("logout", () => {
let userName = idToUsers[socket.id];
delete users[userName];
delete idToUsers[socket.id];
socket.disconnet();
});
});
// Server starts listening
http.listen(port, () => console.log(`App Online`))