-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
67 lines (54 loc) · 1.42 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 http = require('http');
const socketio = require('socket.io');
const fs = require('fs');
// HTTPサーバを生成する
const server = http.createServer(function(req, res) {
const url = "app" + (req.url.endsWith("/") ? req.url + "index.html" : req.url);
console.log(url);
if (fs.existsSync(url)) {
fs.readFile(url, (err, data) => {
if (!err) {
res.writeHead(200, {'Content-Type' : getType(url)});
res.end(data);
} else {
res.statusCode = 500;
res.end();
}
});
} else {
res.statusCode = 404;
res.end();
}
});
// Listen
const port = process.env.PORT || 7000;
server.listen(port, function() {
// console.log("Listening on: http://localhost:" + port);
});
function getType(_url) {
const types = {
".html": "text/html",
".css": "text/css",
".js": "text/javascript",
".png": "image/png",
".gif": "image/gif",
".svg": "svg+xml"
};
for (let key in types) {
if (_url.endsWith(key)) {
return types[key];
}
}
return "text/plain";
}
// HTTPサーバにソケットをひも付ける(WebSocket有効化)
const io = socketio.listen(server);
io.sockets.on('connection', (socket) => {
socket
.on('client_to_server', function(data) {
io.sockets.emit('server_to_client', {value: data.value});
})
.on('update_sliderparams', (data) => {
socket.broadcast.emit('update_sliderparams', data);
})
});