This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (54 loc) · 1.44 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
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// Define static assets directory
app.use('/public', express.static(__dirname + '/public'));
// Default route send client app
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
// 301 redirect all requests to www
app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if(host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, "http://www." + host);
}
});
server.listen(8080);
// WebSocket
io.on('connection', function(socket) {
console.log('client connected');
// Relay sample triggers
socket.on('trigger', function(data) {
var obj = JSON.parse(data);
if(typeof obj.room !== 'undefined') {
socket.broadcast.to(obj.room).emit('trigger', data);
} else {
socket.broadcast.emit('trigger', data);
}
console.log(obj);
});
// Relay chat messages
socket.on('chat', function(data) {
var obj = JSON.parse(data);
if(typeof obj.room !== 'undefined') {
socket.broadcast.to(obj.room).emit('chat', data);
} else {
socket.broadcast.emit('chat', data);
}
console.log(obj);
});
// Join room
socket.on('join', function(room) {
socket.join(room);
console.log('joining room', room);
});
// Leave room
socket.on('leave', function(room) {
socket.leave(room);
console.log('leaving room', room);
});
});