Skip to content

Commit

Permalink
allow multiple peer connections, by first disconnecting others (for i…
Browse files Browse the repository at this point in the history
…ssue cvan#48)
  • Loading branch information
cvan committed Sep 8, 2017
1 parent fa234ca commit f07b054
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,6 @@ peer.on('data', function (data) {
console.log('data received:', data);
});

peer.on('busy', function () {
console.error('`pairCode` "%s" is already in use', peer.pairCode);
});

peer.on('rtc.signal', function () {
console.log('WebRTC signalling');
});
Expand All @@ -78,6 +74,10 @@ peer.on('downgrade', function () {
console.log('downgraded WebRTC peer connection ⇒ to WebSocket connection');
});

peer.on('warning', function (data) {
console.error('warning:', data.message);
});

peer.on('error', function (err) {
console.error('error:', err);
});
Expand Down
35 changes: 25 additions & 10 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,21 @@ function SocketPeerServer (opts) {
var peersWaiting = Object.create(null);
var connections = Object.create(null);

function closeConnection (pairCode) {
function closeConnection (pairCode, filter) {
if (!filter) {
// Create a no-op function.
filter = x => x;
}
let matched = false;
connections[pairCode].forEach(conn => {
conn.peer = null;
matched = filter(conn);
if (matched) {
conn.peer = null;
}
});
connections[pairCode] = null;
if (matched) {
connections[pairCode] = null;
}
}

function sendMessage (type, data) {
Expand Down Expand Up @@ -100,8 +110,13 @@ function SocketPeerServer (opts) {
console.log('[pair] Received pairCode:', pairCode);

if (connections[pairCode]) {
client.sendMessage('busy');
return;
client.sendMessage('warning', {
message: '`pairCode` "' + pairCode + '" is already in use',
pairCode: pairCode
});
closeConnection(pairCode, function (clientToCheck) {
return clientToCheck !== client;
});
}

client.pairCode = pairCode;
Expand Down Expand Up @@ -143,14 +158,14 @@ function SocketPeerServer (opts) {
});

client.on('close', () => {
if (client.pairCode in peersWaiting &&
peersWaiting[client.pairCode] === client) {
peersWaiting[client.pairCode] = null;
const pairCode = client.pairCode;
if (pairCode in peersWaiting && peersWaiting[pairCode] === client) {
peersWaiting[pairCode] = null;
}

if (client.peer) {
peersWaiting[client.pairCode] = client.peer;
closeConnection(client.pairCode);
peersWaiting[pairCode] = client.peer;
closeConnection(pairCode);
}
});
});
Expand Down

0 comments on commit f07b054

Please sign in to comment.