-
Notifications
You must be signed in to change notification settings - Fork 1
/
simpleNodeServer_OK.js
69 lines (55 loc) · 1.84 KB
/
simpleNodeServer_OK.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
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'));
io.on('connection', function(socket){
console.log('a user connected');
socket.on('message', function(msg){
io.to(msg.channel).emit('message', msg);
console.log('S --> Got message: ', msg);
});
//socket.on('create or join', function (channel) {
//socket.join(channel);
//io.to(channel).emit('created', channel);
//});
socket.on('create or join', function (channel) {
var clients = io.sockets.adapter.rooms[channel];
var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0;
console.log('numclients = ' + numClients);
// First client joining...
if (numClients == 0){
socket.join(channel);
io.to(channel).emit('created', channel);
// Second client joining...
} else if (numClients == 1) {
// Inform initiator...
io.to(channel).emit('remotePeerJoining', channel);
// Let the new peer join channel
socket.join(channel);
socket.broadcast.to(channel).emit('broadcast: joined', 'S --> broadcast(): client ' + socket.id + ' joined channel ' + channel);
} else { // max two clients
console.log("Channel full!");
socket.emit('full', channel);
}
});
socket.on('response', function(response) {
io.emit('response', response);
console.log('S --> Got response: ', response);
});
socket.on('Bye', function(channel) {
// Notify other peer
io.emit('Bye');
socket.disconnect();
});
socket.on('Ack', function() {
console.log('Got an Ack!');
socket.disconnect();
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});