-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
65 lines (55 loc) · 1.55 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
var connect = require('connect'),
http = require('http'),
socketio = require('socket.io'),
unmatchedUsers = [];
app = http.createServer(connect().use(connect.static('app')));
io = socketio.listen(app);
io.configure(function () {
io.set("transports", ["websocket"]);
});
app.listen(process.env.PORT || 1337);
io.sockets.on('connection', function (socket) {
var partner = null;
function findNewPartner() {
if (unmatchedUsers.length > 0) {
var user = unmatchedUsers.shift();
partner = user.socket;
user.setPartner(socket);
socket.emit("new", null);
partner.emit("new", null);
} else {
unmatchedUsers.push({
"socket": socket,
"setPartner": function(skt) {
partner = skt;
}
});
}
}
socket.on('leave', leave);
socket.on('msg', function(data) {
partner.emit('msg', data);
});
socket.on('new', function() {
findNewPartner();
});
socket.on('disconnect', leave);
function leave() {
var idx = indexOfSocket();
if (idx >= 0) {
unmatchedUsers.splice(idx, 1);
}
if (partner) {
partner.emit('leave', null);
partner = null;
}
}
function indexOfSocket() {
for (var idx = 0; idx < unmatchedUsers.length; idx++) {
if (unmatchedUsers[idx].socket.id === socket.id) {
return idx;
}
}
return -1;
}
});