-
Notifications
You must be signed in to change notification settings - Fork 1
/
completeNodeServerWithDataChannel.js
58 lines (46 loc) · 1.83 KB
/
completeNodeServerWithDataChannel.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
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static('public'));
// Let's start managing connections...
io.on('connection', function(socket){
// Handle 'message' messages
socket.on('message', function (message) {
log('S --> got message: ', message);
// channel-only broadcast...
io.emit('message', message);
});
// Handle 'create or join' messages
socket.on('create or join', function (room) {
var clients = io.sockets.adapter.rooms[room];
var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0;
log('S --> Room ' + room + ' has ' + numClients + ' client(s)');
log('S --> Request to create or join room', room);
// First client joining...
if (numClients == 0){
socket.join(room);
socket.emit('created', room);
} else if (numClients == 1) {
// Second client joining...
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room);
} else { // max two clients
socket.emit('full', room);
}
});
function log(){
var array = [">>> "];
for (var i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});