-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
executable file
·93 lines (72 loc) · 2.56 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
/**
* Server module.
*
*
*/
'use strict';
var nodestatic = require('node-static');
var express = require('express');
var path = require('path');
var serverPort = process.env.OPENSHIFT_NODEJS_PORT || 1337
var serverIpAddress = process.env.OPENSHIFT_NODEJS_IP || 'localhost'
var socketIoServer = '127.0.0.1';
////////////////////////////////////////////////
// SETUP SERVER
////////////////////////////////////////////////
var app = express();
require('./router')(app, socketIoServer);
// Static content (css, js, .png, etc) is placed in /public
app.use(express.static(__dirname + '/public'));
// Location of our views
app.set('views',__dirname + '/views');
// Use ejs as our rendering engine
app.set('view engine', 'ejs');
// Tell Server that we are actually rendering HTML files through EJS.
app.engine('html', require('ejs').renderFile);
var server=app.listen(serverPort, serverIpAddress, function(){
console.log("Express is running on port "+serverPort);
});
var io = require('socket.io').listen(server);
////////////////////////////////////////////////
// EVENT HANDLERS
////////////////////////////////////////////////
io.sockets.on('connection', function (socket){
function log(){
var array = [">>> Message from server: "];
for (var i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
socket.on('message', function (message) {
log('Got message: ', message);
socket.broadcast.to(socket.room).emit('message', message);
});
socket.on('create or join', function (message) {
var room = message.room;
socket.room = room;
var participantID = message.from;
configNameSpaceChannel(participantID);
var numClients = io.sockets.clients(room).length;
log('Room ' + room + ' has ' + numClients + ' client(s)');
log('Request to create or join room', room);
if (numClients == 0){
socket.join(room);
socket.emit('created', room);
} else {
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room);
}
});
// Setup a communication channel (namespace) to communicate with a given participant (participantID)
function configNameSpaceChannel(participantID) {
var socketNamespace = io.of('/'+participantID);
socketNamespace.on('connection', function (socket){
socket.on('message', function (message) {
// Send message to everyone BUT sender
socket.broadcast.emit('message', message);
});
});
}
});