-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (39 loc) · 1.18 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
const express = require('express')
const app = express()
const exphbs = require('express-handlebars');
const port = process.env.PORT || 9090;
//set the template engine ejs
app.engine('.hbs', exphbs({
extname: '.hbs'
}));
app.set('view engine', '.hbs');
//middlewares
app.use('/public', express.static('public'));
//routes
app.get('/', function(req, res){
res.render('home');
})
//Listen on port
server = app.listen(port);
console.log(port);
//socket.io instantiation
const io = require("socket.io")(server)
//listen on every connection
io.on('connection', function(socket){
console.log('New user connected')
//default username
socket.username = "Anonymous"
//listen on change_username
socket.on('change_username', function(data){
socket.username = data.username
})
//listen on new_message
socket.on('new_message', function(data){
//broadcast the new message
io.sockets.emit('new_message', {message : data.message, username : socket.username});
})
//listen on typing
socket.on('typing', function(data){
socket.broadcast.emit('typing', {username : socket.username})
})
})