-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
60 lines (48 loc) · 1.67 KB
/
Copy pathapp.js
File metadata and controls
60 lines (48 loc) · 1.67 KB
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
const http=require('http');
const path=require('path');
var express=require('express');
const formatmsg=require('./utilis/messages')
const socketio=require('socket.io');
const botname='Chatbot';
const {userJion,getcurruser,userleave,getroomusers}=require('./utilis/user');
var app=express();
const server=http.createServer(app);
const io=socketio(server);
var port=process.env.PORT||3000;
const publicDir=path.join(__dirname,'public');
app.use(express.static(publicDir))
io.on('connection',socket=>{
socket.on('joinroom',({username,room})=>{
const user=userJion(socket.id,username,room)
socket.join(user.room)
//welcome cureent user
socket.emit('message',formatmsg(botname,'Welcome to chat app'))
//broadcast when a user connects
socket.broadcast.to(user.room).emit('message',formatmsg(botname,` ${username} has joined the chat`))
//send users info
io.to(user.room).emit('roomusers',{
room:user.room,
users:getroomusers(user.room)
})
})
socket.on('chatMessage',msg=>{
const user=getcurruser(socket.id);
io.to(user.room).emit('message',formatmsg(user.username,msg))
})
//this runs when somwone disconnect
socket.on('disconnect',()=>{
const user=userleave(socket.id);
if(user){
io.to(user.room).emit('message',formatmsg(botname,`${user.username} has left the chat`))
//remove forom frontend users
//send users info
io.to(user.room).emit('roomusers',{
room:user.room,
users:getroomusers(user.room)
})
}
})
})
server.listen(port,()=>{
console.log(`server has started at port ${port}`)
})