-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (37 loc) · 1.59 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
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const cors = require('cors');
const moment = require('moment')
const { addUser, removeUser, getUser, getUsersInRoom } = require('./users.js');
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(cors());
app.use(router);
io.on('connect', (socket) => {
socket.on('join', ({ name, room }, callback) => {
console.warn('user name is ',name);
const { error, user } = addUser({ id: socket.id, name, room });
if(error) return callback(error);
socket.join(user.room);
socket.emit('message', { user: 'admin', text: `${user.name}, welcome to room ${user.room}.` , time : moment().format('h:mm A')});
socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name} has joined!`});
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room) });
callback();
});
socket.on('sendMessage', (message, callback) => {
const user = getUser(socket.id);
io.to(user.room).emit('message', { user: user.name, text: message, time : moment().format('h:mm A')});
callback();
});
socket.on('disconnect', () => {
const user = removeUser(socket.id);
if(user) {
io.to(user.room).emit('message', { user: 'Admin', text: `${user.name} has left.` });
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room)});
}
})
});
server.listen(process.env.PORT || 5000, () => console.log(`Server has started.`));