Browse Source

added rooms and abstracted away the server code

Dennis Mårtensson 12 years ago
parent
commit
22e6fc859e
5 changed files with 149 additions and 98 deletions
  1. 26 6
      example/index.html
  2. 3 1
      lib/io.js
  3. 1 1
      package.json
  4. 10 90
      server.js
  5. 109 0
      webrtc.io.js

+ 26 - 6
example/index.html

@@ -14,6 +14,7 @@
     </div>
     <div id="chatbox">
       <button id="fullscreen">Enter Full Screen</button>
+      <button id="newRoom">Create A New Room</button>
       <div id="messages">
       </div>
       <br>
@@ -110,7 +111,7 @@
         return msg.replace(/</g, '&lt;');
       }
 
-      function initFullScreen(){ 
+      function initFullScreen() { 
         var button = document.getElementById("fullscreen");
         button.addEventListener('click', function(event) {
           var elem = document.getElementById("videos"); 
@@ -119,6 +120,24 @@
         });
       } 
 
+      function initNewRoom() {
+        var button = document.getElementById("newRoom");
+
+        button.addEventListener('click', function(event) {
+
+            var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
+            var string_length = 8;
+            var randomstring = '';
+            for (var i=0; i<string_length; i++) {
+              var rnum = Math.floor(Math.random() * chars.length);
+              randomstring += chars.substring(rnum,rnum+1);
+            }
+            
+            window.location.hash = randomstring;
+            location.reload();
+        })
+      }
+
       function init() {
         rtc.createStream('you', function(stream) {
           videos.push(document.getElementById('you'));
@@ -126,7 +145,10 @@
           subdivideVideos();
         });
 
-        rtc.connect("http://multiwebrtc.nodejitsu.com/");
+        var room = window.location.hash.slice(1);
+
+        rtc.connect("http://multiwebrtc.nodejitsu.com/", room);
+
         rtc.on('add remote stream', function(stream, socketId) {
           console.log("ADDING REMOTE STREAM...");
           var clone = cloneVideo('you', socketId);
@@ -139,15 +161,13 @@
         });
         initChat();
         initFullScreen();
+        initNewRoom();
       }
       
-      function onClose(data) {
-//        video.parentNode.removeChild(video);
-      }
-
       window.onresize = function(event) {
         subdivideVideos();
       };
+
     </script>
   </body>
 </html>

+ 3 - 1
lib/io.js

@@ -30,9 +30,11 @@ rtc.initializedStreams = 0;
 /**
  * Connects to the socket.io server.
  */
-rtc.connect = function(server) {
+rtc.connect = function(server, room) {
+  room = room || ''; // by default, join a room called the blank string
   rtc._socket = io.connect(server);
   rtc._socket.on('connect', function() {
+    rtc._socket.emit('join room', room);
     rtc.fire('connect');
   });
 

+ 1 - 1
package.json

@@ -1,7 +1,7 @@
 {
   "name": "MultiWebRTC",
   "description": "Example of multi user webrtc",
-  "version": "0.0.1-15",
+  "version": "0.0.1-17",
   "engines": {
     "node": ">= 0.6.0"
   },

+ 10 - 90
server.js

@@ -1,5 +1,7 @@
-var app = require('express').createServer()
-  , io = require('socket.io').listen(app);
+var app = require('express').createServer();
+var io = require('./webrtc.io').listen(app);
+
+var colors = {};
 
 app.listen(80);
 
@@ -15,98 +17,16 @@ app.get('/io.js', function (req, res) {
   res.sendfile(__dirname + '/lib/io.js');
 });
 
-var connections = [];
-var colors = {};
-
 io.sockets.on('connection', function(socket) {
   console.log("connection received");
-  connections.push(socket);
-  colors[socket.id] = Math.floor(Math.random()* 0xFFFFFF)
-
-  var connectionsId = [];
-
-  for (var i = 0, len = connections.length; i < len; i++) {
-    var id = connections[i].id;
-
-    if (id !== socket.id) {
-      connectionsId.push(id);
-    }
-  }
-
-  socket.emit('get peers', {
-    connections: connectionsId
-  });
-
-  socket.broadcast.emit('new peer connected', { socketId: socket.id });
-
-  socket.on('disconnect', function() {
-
-    for (var i = 0; i < connections.length; i++) {
-      var id = connections[i].id;
-
-      if (id == socket.id) {
-        connections.splice(i, 1);
-        i--;
-        socket.broadcast.emit('remove peer connected', { socketId: socket.id });
-      }
-    }
-  });
-
-  socket.on('receive ice candidate', function(data) {
-    console.log("ice candidate received");
-
-    var soc = getSocket(data.socketId);
-
-    if (soc) {
-      soc.emit('receive ice candidate', {
-        label: data.label,
-        candidate: data.candidate,
-        socketId: socket.id
-      });
-    }
-  });
-
-  socket.on('send offer', function(data) {
-    console.log("offer received");
-
-    var soc = getSocket(data.socketId);
-
-    if (soc) {
-      soc.emit('receive offer', {
-        sdp: data.sdp,
-        socketId: socket.id
-      });
-    }
-  });
-
-  socket.on('send answer', function(data) {
-    console.log("answer received");
-
-    var soc = getSocket(data.socketId);
-
-    if (soc) {
-      soc.emit('receive answer', {
-        sdp: data.sdp,
-        socketId: socket.id
-      });
-    }
-  });
-
 
+  colors[socket.id] = Math.floor(Math.random()* 0xFFFFFF)
   socket.on('chat msg', function(msg) {
     console.log("chat received");
     
-    socket.broadcast.emit('receive chat msg', { msg: msg, color: colors[socket.id]});
+    socket.broadcast.emit('receive chat msg', {
+      msg: msg,
+      color: colors[socket.id]
+    });
   });
-
-});
-
-
-function getSocket(id) {
-  for (var i = 0; i < connections.length; i++) {
-    var socket = connections[i];
-    if (id === socket.id) {
-      return socket;
-    }
-  }
-}
+});

+ 109 - 0
webrtc.io.js

@@ -0,0 +1,109 @@
+var io = require('socket.io');
+
+var rooms = {};
+
+module.exports.listen = function() {
+  // delegate all arguments to socket.io.listen
+  var manager = io.listen.apply(io, arguments);
+
+  manager.sockets.on('connection', function(socket) {
+    // TODO: let you join multiple rooms
+    socket.on('join room', function(room) {
+      // initialize room as an empty array
+      var connections = rooms[room] = rooms[room] || [];
+
+      socket.join(room);
+
+      // tell everyone else in the room about the new peer
+      socket.broadcast.to(room)
+        .emit('new peer connected', { socketId: socket.id });
+
+      connections.push(socket);
+
+      // pass array of connection ids except for peer's to peer
+      var connectionsId = [];
+      for (var i = 0, len = connections.length; i < len; i++) {
+        var id = connections[i].id;
+
+        if (id !== socket.id) {
+          connectionsId.push(id);
+        }
+      }
+
+      socket.emit('get peers', {
+        connections: connectionsId
+      });
+
+      // remove connection from array and tell everyone else about the
+      // disconnect
+      socket.on('disconnect', function() {
+        var connections = rooms[room];
+        for (var i = 0; i < connections.length; i++) {
+          var id = connections[i].id;
+
+          if (id == socket.id) {
+            connections.splice(i, 1);
+            i--;
+            socket.broadcast.to(room).emit('remove peer connected', {
+              socketId: socket.id
+            });
+          }
+        }
+      });
+
+      socket.on('receive ice candidate', function(data) {
+        var soc = getSocket(room, data.socketId);
+
+        if (soc) {
+          soc.emit('receive ice candidate', {
+            label: data.label,
+            candidate: data.candidate,
+            socketId: socket.id
+          });
+        }
+      });
+
+      socket.on('send offer', function(data) {
+        var soc = getSocket(room, data.socketId);
+
+        if (soc) {
+          soc.emit('receive offer', {
+            sdp: data.sdp,
+            socketId: socket.id
+          });
+        }
+      });
+
+      socket.on('send answer', function(data) {
+        var soc = getSocket(room, data.socketId);
+
+        if (soc) {
+          soc.emit('receive answer', {
+            sdp: data.sdp,
+            socketId: socket.id
+          });
+        }
+      });
+    });
+
+
+  });
+
+  return manager;
+}
+
+function getSocket(room, id) {
+  var connections = rooms[room];
+
+  if (!connections) {
+    // TODO: Or error, or customize
+    return;
+  }
+
+  for (var i = 0; i < connections.length; i++) {
+    var socket = connections[i];
+    if (id === socket.id) {
+      return socket;
+    }
+  }
+}