-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
48 lines (33 loc) · 971 Bytes
/
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
47
48
const express = require('express')
const app = express()
//set the template engine ejs
app.set('view engine', 'ejs')
//middlewares
app.use(express.static('public'))
//routes
app.get('/', (req, res) => {
res.render('index')
})
//Listen on port 3000
server = app.listen(3000)
//socket.io instantiation
const io = require("socket.io")(server)
//listen on every connection
io.on('connection', (socket) => {
console.log('New user connected')
//default username
socket.username = "Anonymous"
//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 message
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})
})
})