-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (53 loc) · 2.08 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
77
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const { SocketAddress } = require('net');
const formatMessage = require('./utils/messages');
const {userJoin, getCurrentUser, userLeave, getRoomUsers} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = 'Chatbot';
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', socket=>{
socket.on('joinroom', ({username, room})=>{
const user = userJoin(socket.id, username, room);
console.log(`${username} has joined`);
socket.join(user.room);
// Welcome new connected user.
socket.emit('message', formatMessage(botName, 'Welcome to chatroom!') );
// Broadcast when a user connection(everyone else in room except user who connected.)
socket.broadcast
.to(user.room)
.emit('message',formatMessage(botName, `${user.username} has joined the chat`)
);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Listening to user's messages and sending them respectively.
socket.on('chatMessage', (message)=>{
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, message));
});
// When user disconnects
socket.on('disconnect', ()=>{
const user = userLeave(socket.id);
if(user){
console.log(`${user.username} has left`);
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)
});
}
});
});
const PORT = process.env.PORT || 3005;
server.listen(PORT,'0.0.0.0',()=>{
console.log('Server is up');
});