-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
101 lines (78 loc) · 2.17 KB
/
Copy pathindex.js
File metadata and controls
101 lines (78 loc) · 2.17 KB
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
94
95
96
97
98
99
100
101
'use strict';
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
debug('a user connected');
socket.emit('connection');
socket.on('register as server', function(name) {
var clientRoom = 'clients:' + name;
// close other sockets in the clients room
var room = findClientsSocket(clientRoom);
room.forEach(function(client) {
client.disconnect();
});
// create the room
Server(socket, name);
});
socket.on('register as client', function(name) {
Client(socket, name);
});
});
http.listen(3000, function() {
debug('listening on *:3000');
});
function Server(socket, name) {
var serverRoom = 'server:' + name;
debug('server registered: ' + serverRoom);
socket.join(serverRoom);
// disconnection
socket.on('disconnect', function() {
debug('server disconnected');
});
socket.emit('registered as server');
}
function Client(socket, name) {
debug('a client registered');
var clientRoom = 'clients:' + name;
var serverRoom = 'server:' + name;
socket.join(clientRoom);
socket.broadcast.to(serverRoom).emit('client connection', { id: socket.id });
// message
socket.on('message', function(msg) {
msg.id = socket.id;
socket.broadcast.to(serverRoom).emit('message', msg);
});
// disconnection
socket.on('disconnect', function() {
debug('user disconnected');
});
socket.emit('registered as client');
}
function debug() {
var i;
console.log('\n===== DEBUG ======');
for (i in arguments) {
console.log(arguments[i]);
}
}
function findClientsSocket(roomId, namespace) {
var res = []
, ns = io.of(namespace ||"/"); // the default namespace is "/"
if (ns) {
for (var id in ns.connected) {
if(roomId) {
var index = ns.connected[id].rooms.indexOf(roomId) ;
if(index !== -1) {
res.push(ns.connected[id]);
}
} else {
res.push(ns.connected[id]);
}
}
}
return res;
}