-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
101 lines (79 loc) · 3.14 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const formatMessage = require('./utils/messages');
const { userJoin, getCurrentUser, userLeave, getRoomUsers } = require('./utils/users');
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
// Routing
app.use(express.static(path.join(__dirname, 'public')));
const botName = ' Bot';
const ACCEPTED_ROOMS = ["1", "2"];
// Run when client connets
io.on('connection', socket => {
socket.on('joinRoom', ({ userPeerId, username, room }) => {
if (!ACCEPTED_ROOMS.includes(room)) {
socket.emit('roomNotValid');
}
const user = userJoin(userPeerId, username, room);
if (!user) {
socket.emit('sameName');
} else {
socket.join(user.room);
// only show in client to the user connecting
socket.emit('message', formatMessage(botName, 'Welcome to Zoom Clone!'));
// Broadcast to all except the user itself in a specif room
socket.broadcast
.to(user.room).emit(
'message',
formatMessage(botName, `${user.username} has joined the chat`)
);
socket.broadcast.to(user.room).emit('user-connected', userPeerId)
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
socket.on('typing', () => {
console.log('typing');
socket.broadcast
.to(user.room)
.emit('typing', {
username: user.username
});
});
socket.on('stop typing', () => {
console.log('stop typing');
socket.broadcast
.to(user.room)
.emit('stop typing', {
username: user.username
});
});
// Listen for chatMessage
socket.on('chatMessage', msg => {
const user = getCurrentUser(userPeerId);
// Broadcast to all clients in the room
io
.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(userPeerId);
if (user) {
io
.to(user.room)
.emit('message', formatMessage(botName, `${user.username} has left the chat`));
}
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
socket.broadcast.to(user.room).emit('user-disconnected', userPeerId)
});
}
});
});