-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
46 lines (34 loc) · 1.14 KB
/
app.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
const express=require('express');
const app=express();
app.set('view engine','ejs');
app.use(express.static('public'));
app.get('/',(req,res)=>{
res.render('index');
})
server=app.listen(process.env.PORT || 3000);
const io = require("socket.io")(server)
//listen on every connection
io.on('connection',(socket)=>{
// console.log('New user connected');
//default username
socket.username="Anonymus";
//listen on change username
socket.on('change_username',(data)=>{
socket.username=data.username;
})
//listen on new message
socket.on('new_message', (data)=>{
//broadcast the new messages
io.sockets.emit('new_message', {message: data.message, username:socket.username});
})
//listen on typing
socket.on('typing', (data) => {
socket.broadcast.emit('typing', {username : socket.username})
})
//emit message to all front-end clients
io.sockets.emit('chat message', 'USER '+socket.username+' IS ONLINE');
//handling disconnects
socket.on('disconnect', function(data) {
io.sockets.emit('chat message', 'USER '+socket.username+' DISCONNECTED');
});
})