forked from DevilsAutumn/AurBta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
71 lines (47 loc) · 1.87 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
const express = require('express');
const path = require('path');
const http = require('http');
const socket = require('socket.io');
const formatMessage = require('./utils/messages');
const { userJoin, getCurrentUser, userLeave, getRoomUers } = require('./utils/users');
const app = express();
const server = http.createServer(app)
const io = socket(server);
//set static folder
app.use(express.static(path.join(__dirname, 'public')));
const botname = 'Aurbta';
//runs when client connects
io.on('connection', socket => {
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
//welcome current user
socket.emit('user-joined', formatMessage(botname, 'Welcome to AurBta!'));
//Broadcast when a user connects
socket.broadcast.to(user.room).emit('user-joined', formatMessage(botname, `${user.username} has joined the chat!`));
//send user and chat info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUers(user.room)
});
});
//listen for chat message
socket.on('chatMessage', (msg) => {
const user = getCurrentUser(socket.id);
socket.broadcast.to(user.room).emit('messageReceived', formatMessage(user.username, msg));
});
//runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if (user) {
io.to(user.room).emit('leaving', formatMessage(botname, `${user.username} has left the chat`));
//send user and chat info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUers(user.room)
});
};
});
});
const PORT = process.env.PORT;
server.listen(PORT, () => console.log(`Server runnning on port ${PORT}`));