-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
81 lines (65 loc) · 2.38 KB
/
server.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
77
78
79
80
81
const express = require('express');
const socket = require('socket.io');
const path = require('path');
require('dotenv/config');
const app = express();
const {addUser, removeUser, getUser, getUsersInRoom ,getUserInRoomCount} = require('./users.js');
if(process.env.NODE_ENV=== 'production'){
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log('App started at port');
})
const canvasData = {};
const io = socket(server);
io.sockets.on('connection', (socket) => {
console.log("New connection made => " + socket.id);
let userObj;
socket.on('newConnection', (data) => {
console.log(data.roomName + " -> " + data.userName);
const {error, user} = addUser(socket.id,data.roomName, data.userName);
if(error){
console.log('--------------------------------------');
console.log(error);
socket.emit('errorConnection', error);
}else{
if(canvasData[user.room] == null){
canvasData[user.room] = [];
}
userObj = user;
socket.join(user.room);
io.sockets.in(user.room).emit('canvasData', canvasData[user.room]);
io.sockets.in(user.room).emit('snackMessage', `${user.name} has joined the room.`);
io.sockets.in(user.room).emit('userChange', getUserInRoomCount(user.room));
}
})
socket.on('clearBoard', (data) => {
if(userObj){
console.log(userObj);
canvasData[userObj.room].length = 0;
io.sockets.in(userObj.room).emit('clearBoard');
io.sockets.in(userObj.room).emit('snackMessage', `${userObj.name} has cleared the canvas.`);
}
})
socket.on('draw', (data) => {
if(userObj){
canvasData[userObj.room].push(data);
socket.broadcast.to(userObj.room).emit('draw', data);
}
});
socket.on('disconnect', () => {
removeUser(socket.id);
if(userObj){
io.sockets.in(userObj.room).emit('userChange', getUserInRoomCount(userObj.room));
io.sockets.in(userObj.room).emit('snackMessage', `${userObj.name} has left the room.`);
if(getUserInRoomCount(userObj.room) == 0){
canvasData[userObj.room].length = 0;
}
}
console.log("User Disconnected");
})
})