-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
67 lines (57 loc) · 1.83 KB
/
server.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
55
56
57
58
59
60
61
62
63
64
65
66
67
const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require("socket.io")
const io = new Server(server)
const port = process.env.PORT || 8080
const fs = require('fs-extra')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
})
app.get('/chat', (req, res) => {
res.sendFile(__dirname + '/views/chat.html')
})
io.on('connection', (socket) => {
socket.emit('no broadcast connected')
socket.on('i connected', nameOfPersonThatConnected => {
socket.broadcast.emit('i connected', nameOfPersonThatConnected)
socket.user = nameOfPersonThatConnected
fs.readJson('./public/json/connections.json', (err, obj) => {
if (err) console.error(err)
fs.writeJson('./public/json/connections.json', {
connected: obj.connected + 1
})
.then(() => {
socket.broadcast.emit('someone connected')
socket.emit('no broadcast connected')
})
.catch(err => {
console.error(err)
})
})
})
socket.on('disconnect', () => {
socket.broadcast.emit('someone disconnected', socket.user)
fs.readJson('./public/json/connections.json', (err, obj) => {
if (err) console.error(err)
fs.writeJson('./public/json/connections.json', {
connected: obj.connected - 1
})
.then(() => {})
.catch(err => {
console.error(err)
})
})
})
socket.on('new chat message', (msg, userSent, userImgUrl, userInnerHtml) => {
socket.broadcast.emit('new chat message', msg, userSent, userImgUrl, userInnerHtml)
})
socket.on('i changed name', newUserName => {
socket.user = newUserName
})
})
server.listen(port, () => {
console.log('Listening app at http://localhost:' + port)
})