Merge pull request #1 from ianramzy/multiple-rooms

add Multiple rooms
This commit is contained in:
Ian Ramzy 2020-03-22 13:13:29 -04:00 committed by GitHub
commit 768375bc60
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 75 additions and 68 deletions

View File

@ -1,22 +1,23 @@
require('dotenv').config(); require('dotenv').config();
// Twilio init var twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
var twilio = require('twilio')(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
var express = require('express'); var express = require('express');
var app = express(); var app = express();
var http = require('http').createServer(app); var http = require('http').createServer(app);
var io = require('socket.io')(http); var io = require('socket.io')(http);
app.use(express.static('public')); app.use(express.static('public'));
function log(msg, room) {
console.log(room + ": " + msg)
}
// When a socket connects, set up the specific listeners we will use. // When a socket connects, set up the specific listeners we will use.
io.on('connection', function (socket) { io.on('connection', function (socket) {
// When a client tries to join a room, only allow them if they are first or // When a client tries to join a room, only allow them if they are first or
// second in the room. Otherwise it is full. // second in the room. Otherwise it is full.
socket.on('join', function (room) { socket.on('join', function (room) {
console.log('A client joined room:' + room); log('A client joined the room', room);
var clients = io.sockets.adapter.rooms[room]; var clients = io.sockets.adapter.rooms[room];
var numClients = typeof clients !== 'undefined' ? clients.length : 0; var numClients = typeof clients !== 'undefined' ? clients.length : 0;
if (numClients === 0) { if (numClients === 0) {
@ -24,47 +25,46 @@ io.on('connection', function(socket){
} else if (numClients === 1) { } else if (numClients === 1) {
socket.join(room); socket.join(room);
// When the client is second to join the room, both clients are ready. // When the client is second to join the room, both clients are ready.
console.log('Broadcasting ready message') log('Broadcasting ready message', room);
socket.broadcast.emit('willInitiateCall', room); socket.broadcast.to(room).emit('willInitiateCall', room);
socket.emit('ready', room); socket.emit('ready', room).to(room);
socket.broadcast.emit('ready', room); socket.broadcast.to(room).emit('ready', room);
} else { } else {
console.log("room full"); log("room already full", room);
socket.emit('full', room); socket.emit('full', room);
} }
}); });
// When receiving the token message, use the Twilio REST API to request an // When receiving the token message, use the Twilio REST API to request an
// token to get ephemeral credentials to use the TURN server. // token to get ephemeral credentials to use the TURN server.
socket.on('token', function(){ socket.on('token', function (room) {
console.log('Received token request'); log('Received token request', room);
twilio.tokens.create(function (err, response) { twilio.tokens.create(function (err, response) {
if (err) { if (err) {
console.log(err); log(err, room);
} else { } else {
// Return the token to the browser. log('Token generated. Returning it to the browser client', room);
console.log('Token generated. Returning it to the client'); socket.emit('token', response).to(room);
socket.emit('token', response);
} }
}); });
}); });
// Relay candidate messages // Relay candidate messages
socket.on('candidate', function(candidate){ socket.on('candidate', function (candidate, room) {
console.log('Received candidate. Broadcasting...'); log('Received candidate. Broadcasting...', room);
socket.broadcast.emit('candidate', candidate); socket.broadcast.to(room).emit('candidate', candidate);
}); });
// Relay offers // Relay offers
socket.on('offer', function(offer){ socket.on('offer', function (offer, room) {
console.log('Received offer. Broadcasting...'); log('Received offer. Broadcasting...', room);
socket.broadcast.emit('offer', offer); socket.broadcast.to(room).emit('offer', offer);
}); });
// Relay answers // Relay answers
socket.on('answer', function(answer){ socket.on('answer', function (answer, room) {
console.log('Received answer. Broadcasting...'); log('Received answer. Broadcasting...', room);
socket.broadcast.emit('answer', answer); socket.broadcast.to(room).emit('answer', answer);
}); });
}); });

View File

@ -2,10 +2,9 @@ if (!location.hash) {
// Generate random room name if needed // Generate random room name if needed
var adjectives = ["small", "big", "large", "smelly", "new", "happy", "shiny", "old", "clean", "nice", "bad", "cool", "hot", "cold", "warm", "hungry", "slow", "fast"] var adjectives = ["small", "big", "large", "smelly", "new", "happy", "shiny", "old", "clean", "nice", "bad", "cool", "hot", "cold", "warm", "hungry", "slow", "fast"]
var nouns = ["dog", "bat", "wrench", "apple", "pear", "ghost", "cat", "wolf", "squid", "goat", "snail", "hat", "sock", "plum", "bear", "snake", "turtle", "horse","spoon","fork","spider","tree","chair","table"] var nouns = ["dog", "bat", "wrench", "apple", "pear", "ghost", "cat", "wolf", "squid", "goat", "snail", "hat", "sock", "plum", "bear", "snake", "turtle", "horse","spoon","fork","spider","tree","chair","table"]
var adjective = adjectives[Math.floor(Math.random() * adjectives.length)] var adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
var noun = nouns[Math.floor(Math.random() * nouns.length)] var noun = nouns[Math.floor(Math.random() * nouns.length)];
// var num = Math.floor(Math.ran1dom() * 100) location.hash = adjective + noun
location.hash = adjective + "-" + noun
} }
const roomHash = location.hash.substring(1); const roomHash = location.hash.substring(1);
@ -72,7 +71,9 @@ var VideoChat = {
VideoChat.localVideo.srcObject = stream; VideoChat.localVideo.srcObject = stream;
// Now we're ready to join the chat room. // Now we're ready to join the chat room.
VideoChat.socket.emit('join', roomHash); VideoChat.socket.emit('join', roomHash);
// VideoChat.socket.emit('join', 'test'); default // VideoChat.socket.on('roomtest', (passedRoom) => alert("youre in room: " + passedRoom));
VideoChat.socket.on('temp', () => alert("temp called"));
VideoChat.socket.on('full', VideoChat.chatRoomFull);
VideoChat.socket.on('offer', VideoChat.onOffer); VideoChat.socket.on('offer', VideoChat.onOffer);
VideoChat.socket.on('ready', VideoChat.readyToCall); VideoChat.socket.on('ready', VideoChat.readyToCall);
VideoChat.socket.on('willInitiateCall', () => VideoChat.willInitiateCall = true); VideoChat.socket.on('willInitiateCall', () => VideoChat.willInitiateCall = true);
@ -83,6 +84,12 @@ var VideoChat = {
logIt('No media stream for us.'); logIt('No media stream for us.');
}, },
chatRoomFull: function(){
alert("Chat room is full. Check to make sure you don't have multiple open tabs");
// VideoChat.socket.disconnect()
// todo handle this better
},
// When we are ready to call, enable the Call button. // When we are ready to call, enable the Call button.
readyToCall: function (event) { readyToCall: function (event) {
console.log("readyToCall"); console.log("readyToCall");
@ -97,7 +104,7 @@ var VideoChat = {
console.log("startCall"); console.log("startCall");
logIt('>>> Sending token request...'); logIt('>>> Sending token request...');
VideoChat.socket.on('token', VideoChat.onToken(VideoChat.createOffer)); VideoChat.socket.on('token', VideoChat.onToken(VideoChat.createOffer));
VideoChat.socket.emit('token'); VideoChat.socket.emit('token', roomHash);
// VideoChat.callButton.disabled = true // VideoChat.callButton.disabled = true
}, },
@ -130,7 +137,7 @@ var VideoChat = {
logIt(`<<< Received local ICE candidate from STUN/TURN server (${event.candidate.address})`); logIt(`<<< Received local ICE candidate from STUN/TURN server (${event.candidate.address})`);
if (VideoChat.connected) { if (VideoChat.connected) {
logIt(`>>> Sending local ICE candidate (${event.candidate.address})`); logIt(`>>> Sending local ICE candidate (${event.candidate.address})`);
VideoChat.socket.emit('candidate', JSON.stringify(event.candidate)); VideoChat.socket.emit('candidate', JSON.stringify(event.candidate), roomHash);
} else { } else {
// If we are not 'connected' to the other peer, we are buffering the local ICE candidates. // If we are not 'connected' to the other peer, we are buffering the local ICE candidates.
// This most likely is happening on the "caller" side. // This most likely is happening on the "caller" side.
@ -160,7 +167,7 @@ var VideoChat = {
// and send it over the socket connection to initiate the peerConnection // and send it over the socket connection to initiate the peerConnection
// on the other side. // on the other side.
VideoChat.peerConnection.setLocalDescription(offer); VideoChat.peerConnection.setLocalDescription(offer);
VideoChat.socket.emit('offer', JSON.stringify(offer)); VideoChat.socket.emit('offer', JSON.stringify(offer), roomHash);
}, },
function (err) { function (err) {
logIt("failed offer creation"); logIt("failed offer creation");
@ -184,7 +191,7 @@ var VideoChat = {
VideoChat.peerConnection.createAnswer( VideoChat.peerConnection.createAnswer(
function (answer) { function (answer) {
VideoChat.peerConnection.setLocalDescription(answer); VideoChat.peerConnection.setLocalDescription(answer);
VideoChat.socket.emit('answer', JSON.stringify(answer)); VideoChat.socket.emit('answer', JSON.stringify(answer), roomHash);
}, },
function (err) { function (err) {
logIt("Failed answer creation."); logIt("Failed answer creation.");
@ -200,7 +207,7 @@ var VideoChat = {
console.log("onOffer"); console.log("onOffer");
logIt('<<< Received offer'); logIt('<<< Received offer');
VideoChat.socket.on('token', VideoChat.onToken(VideoChat.createAnswer(offer))); VideoChat.socket.on('token', VideoChat.onToken(VideoChat.createAnswer(offer)));
VideoChat.socket.emit('token'); VideoChat.socket.emit('token', roomHash);
}, },
// When an answer is received, add it to the peerConnection as the remote // When an answer is received, add it to the peerConnection as the remote
@ -214,7 +221,7 @@ var VideoChat = {
VideoChat.localICECandidates.forEach(candidate => { VideoChat.localICECandidates.forEach(candidate => {
// The caller now knows that the callee is ready to accept new ICE candidates, so sending the buffer over // The caller now knows that the callee is ready to accept new ICE candidates, so sending the buffer over
logIt(`>>> Sending local ICE candidate (${candidate.address})`); logIt(`>>> Sending local ICE candidate (${candidate.address})`);
VideoChat.socket.emit('candidate', JSON.stringify(candidate)); VideoChat.socket.emit('candidate', JSON.stringify(candidate), roomHash);
}); });
// Reset the buffer of local ICE candidates. This is not really needed // Reset the buffer of local ICE candidates. This is not really needed
// in this specific client, but it's good practice // in this specific client, but it's good practice