-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
70 lines (59 loc) · 2.27 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
const path = require('path')
const http = require('http')
const express = require('express')
const socketio = require('socket.io')
const formateMessage = require('./util/messages')
const {userJoin,getCurrentUser,userLeave,getRoomUser}= require('./util/user')
const app = express()
const server = http.createServer(app)
const io = socketio(server);
//set static folder
app.use(express.static(path.join(__dirname, 'public')));
const boatname = 'Rsin'
//run when clint connect
io.on('connection', socket => {
// join specific chat room
socket.on('joinRoom', ({ username, room }) => {
// calling fucntion form message this will store user in array anr return user object which added
const user = userJoin(socket.id,username,room);
// here user is a constant which have object of currently added user
// sockect join is a propery by which
socket.join(user.room)
// weclome current user
socket.emit('message', formateMessage(boatname, `Welcome ${user.username} I'm your Bot Rsin`))
//broadcast when a user connects
socket.broadcast.to(user.room)
.emit('message', formateMessage(boatname, `${user.username} joined the chat`));
//send user and room info
io.to(user.room).emit('roomUsers',{
room: user.room,
users:getRoomUser(user.room)
})
})
//listion for chatmessage
socket.on('chatMessage', msg => {
// here user already added in database so we can get
// current user by socket id by our function currentuser
const user = getCurrentUser(socket.id)
io.to(user.room).emit('message', formateMessage(user.username, msg))
});
//run when clint disconenct
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if (user) {
io.to(user.room).emit('message', formateMessage(boatname,`${user.username} has left the chat`));
}
//send user and room info
io.to(user.room).emit('roomUsers',{
room: user.room,
users:getRoomUser(user.room)
})
})
})
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
server.listen(port, () => {
console.log("server is running");
})