-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserve.js
More file actions
76 lines (64 loc) · 1.75 KB
/
serve.js
File metadata and controls
76 lines (64 loc) · 1.75 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* @Name: socketio-chat-application-nodejs
* @Date: 2020-12-07
* @Author: Max Base
* @Repository: https://github.com/BaseMax/socketio-chat-application-nodejs
*/
// import libs
const fs = require("fs")
const ioServer = require("socket.io")
const http = require("http")
const https = require("https")
// headers
const CORS = (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Credentials", "true")
res.setHeader("Access-Control-Allow-Methods", "*")
res.setHeader("Access-Control-Allow-Headers", "*")
if(req.method === "OPTIONS" ) {
res.writeHead(200)
res.end()
return
}
}
// http webserver
const httpServer = http.createServer(CORS)
// https webserver
const httpsServer = https.createServer({
// read certificates from disk
"key": fs.readFileSync("selfsigned.key"),
"cert": fs.readFileSync("selfsigned.crt"),
"ca": fs.readFileSync("selfsigned.ca")
}, CORS)
// port(s)
const httpPort = 9098
const httpsPort = 9099
// socket
const io = ioServer()
// listen port(s)
httpServer.listen(httpPort, function() {
console.log(`Listening HTTP on ${httpPort}`)
})
httpsServer.listen(httpsPort, function() {
console.log(`Listening HTTPS on ${httpsPort}`)
})
// attach socket to webserver(s)
io.attach(httpServer)
io.attach(httpsServer)
members = []
io.on('connection', function(socket) {
console.log('A user connected')
socket.on('set-username', function(data) {
console.log(data)
if(members.indexOf(data) > -1) {
socket.emit('user-exists', data + ' username is taken!')
}
else {
members.push(data)
socket.emit('user-set', {username: data})
}
})
socket.on('message', function(data) {
io.sockets.emit('message', data)
})
})