-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
108 lines (98 loc) · 3.11 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var http = require('http')
var fs = require('fs')
var path = require('path')
const APP_PORT = process.env.APP_PORT || 3000
const app = http.createServer(requestHandler)
app.listen(APP_PORT)
console.log(`🖥 HTTP Server running at ${APP_PORT}`)
// handles all http requests to the server
function requestHandler(request, response) {
console.log(`🖥 Received request for ${request.url}`)
// append /client to serve pages from that folder
var filePath = './client' + request.url
if (filePath == './client/') {
// serve index page on request /
filePath = './client/index.html'
}
var extname = String(path.extname(filePath)).toLowerCase()
console.log(`🖥 Serving ${filePath}`)
var mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
}
var contentType = mimeTypes[extname] || 'application/octet-stream'
fs.readFile(filePath, function (error, content) {
if (error) {
if (error.code == 'ENOENT') {
fs.readFile('./client/404.html', function (error, content) {
response.writeHead(404, { 'Content-Type': contentType })
response.end(content, 'utf-8')
})
} else {
response.writeHead(500)
response.end('Sorry, there was an error: ' + error.code + ' ..\n')
}
} else {
response.writeHead(200, { 'Content-Type': contentType })
response.end(content, 'utf-8')
}
})
}
const io = require('socket.io')(app, {
path: '/socket.io',
})
io.attach(app, {
// includes local domain to avoid CORS error locally
// configure it accordingly for production
cors: {
origin: 'http://localhost',
methods: ['GET', 'POST'],
credentials: true,
transports: ['websocket', 'polling'],
},
allowEIO3: true,
})
// To save the list of users as id:username
var users = {}
io.on('connection', (socket) => {
console.log('👾 New socket connected! >>', socket.id)
// handles new connection
socket.on('new-connection', (data) => {
// captures event when new clients join
console.log(`new-connection event received`, data)
// adds user to list
users[socket.id] = data.username
console.log('users :>> ', users)
// emit welcome message event
socket.emit('welcome-message', {
user: 'server',
message: `Welcome to this Socket.io chat ${data.username}. There are ${
Object.keys(users).length
} users connected`,
})
})
// handles message posted by client
socket.on('new-message', (data) => {
console.log(`👾 new-message from ${data.user}`)
// broadcast message to all sockets except the one that triggered the event
socket.broadcast.emit('broadcast-message', {
user: users[data.user],
message: data.message,
})
})
// handles client disconnected
socket.on('disconnect', () => {
console.log('user disconnected')
socket.broadcast.emit('welcome-message', {
user: 'server',
message: `${users[socket.id]} has left the chat`,
})
delete users[socket.id]
console.log('users :>> ', users)
})
})