为什么不使用类似下面的东西?
无连接池
var net = require('net')
, pendingPair = null;
net.createServer(function(_socket) {
_socket.on('data', function(_data) {
//Parse client data
if(!pendingPair) {
pendingPair = _socket;
} else {
// Now you have a pair!
var p1 = pendingPair
, p2 = _socket;
pendingPair = null;
}
}).listen(6969, '127.0.0.1');
建立连接后,您会立即获得自动配对。您仍然需要在某处跟踪这些套接字以启动客户端和断开连接,但您应该能够摆脱 setIntervals。
带连接池
var net = require('net')
, _ = require('underscore')._
, clients = {}
, games = {};
function setKickTimer(socket) {
socket.kickTimer = setTimeout(function() {
socket.write('kicked\n');
}, 30 * 1000);
}
net.createServer(function(socket) {
socket.id = Math.floor(Math.random() * 1000);
setKickTimer(socket);
clients[socket.id] = socket;
socket.on('data', function(data) {
socket.data = parseData(data);
}
socket.on('close', function(data) {
var opponent = _.find(clients, function(client) { return client.opponentId === socket.id; });
// The opponent is no longer part of a pair.
if(opponent) {
delete opponent.opponentId;
setKickTimer(opponent);
}
delete clients[socket.id];
}
}).listen(6969, '127.0.0.1');
setInterval(function(){
// Get the client ids of clients who are not matched, and randomize the order
var unmatchedClientIds = _.shuffle(_.keys(_.filter(clients, function(client) { return !client.opponentId; })));
while(unmatchedClientIds > 2) {
var c1 = unmatchedClientIds.pop(),
, c2 = unmatchedClientIds.pop();
clearTimeout(clients[c1].kickTimer);
clearTimeout(clients[c2].kickTimer);
clients[c1].opponentId = c2;
clients[c2].opponentId = c1;
}
},2*1000);
这不是一个完整的工作解决方案,但它应该让您了解如何管理断开的连接并将用户从队列中踢出。请注意,我正在使用underscore.js来简化对集合的操作。