-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
54 lines (39 loc) · 1.42 KB
/
app.js
File metadata and controls
54 lines (39 loc) · 1.42 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
const express = require('express');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
var PORT = process.env.PORT || 4000;
//set template engine ejs
app.set('viewengine','ejs');
//middlewares
app.use(express.static('public'));
//routes
app.get('/',(req,res) => {
res.render('index.ejs');
})
//listen on port 3000
server = app.listen(PORT);
const io=require('socket.io')(server);
//listen on every connection
io.on('connection',socket=>{
console.log("new user connected");
//default username
socket.username="Anonymous";
//list on change_username
socket.on('change_username',data=>{
console.log("new user is "+data.username);
socket.username=data.username;
})
//listen on new message
socket.on('new_message',data=>{
//broadcasting new_message to all clients including client of this event
io.sockets.emit('new_message',{message:data.message,username:socket.username})
})
//listen on typing
socket.on('typing',data=>{
//broadcasting typing keyword to all clients excluding client of this event
socket.broadcast.emit('typing',{username:socket.username});
//but here i used only single client at a time so im going with this for now but when multiple clients above one is correct
// io.sockets.emit('typing',{username:socket.username});
})
})