webrtc.io.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. var io = require('socket.io');
  2. var rooms = {};
  3. module.exports.listen = function() {
  4. // delegate all arguments to socket.io.listen
  5. var manager = io.listen.apply(io, arguments);
  6. manager.sockets.on('connection', function(socket) {
  7. // TODO: let you join multiple rooms
  8. socket.on('join room', function(room) {
  9. // initialize room as an empty array
  10. var connections = rooms[room] = rooms[room] || [];
  11. socket.join(room);
  12. // tell everyone else in the room about the new peer
  13. socket.broadcast.to(room)
  14. .emit('new peer connected', { socketId: socket.id });
  15. connections.push(socket);
  16. // pass array of connection ids except for peer's to peer
  17. var connectionsId = [];
  18. for (var i = 0, len = connections.length; i < len; i++) {
  19. var id = connections[i].id;
  20. if (id !== socket.id) {
  21. connectionsId.push(id);
  22. }
  23. }
  24. socket.emit('get peers', {
  25. connections: connectionsId
  26. });
  27. // remove connection from array and tell everyone else about the
  28. // disconnect
  29. socket.on('disconnect', function() {
  30. var connections = rooms[room];
  31. for (var i = 0; i < connections.length; i++) {
  32. var id = connections[i].id;
  33. if (id == socket.id) {
  34. connections.splice(i, 1);
  35. i--;
  36. socket.broadcast.to(room).emit('remove peer connected', {
  37. socketId: socket.id
  38. });
  39. }
  40. }
  41. });
  42. socket.on('receive ice candidate', function(data) {
  43. var soc = getSocket(room, data.socketId);
  44. if (soc) {
  45. soc.emit('receive ice candidate', {
  46. label: data.label,
  47. candidate: data.candidate,
  48. socketId: socket.id
  49. });
  50. }
  51. });
  52. socket.on('send offer', function(data) {
  53. var soc = getSocket(room, data.socketId);
  54. if (soc) {
  55. soc.emit('receive offer', {
  56. sdp: data.sdp,
  57. socketId: socket.id
  58. });
  59. }
  60. });
  61. socket.on('send answer', function(data) {
  62. var soc = getSocket(room, data.socketId);
  63. if (soc) {
  64. soc.emit('receive answer', {
  65. sdp: data.sdp,
  66. socketId: socket.id
  67. });
  68. }
  69. });
  70. });
  71. });
  72. return manager;
  73. }
  74. function getSocket(room, id) {
  75. var connections = rooms[room];
  76. if (!connections) {
  77. // TODO: Or error, or customize
  78. return;
  79. }
  80. for (var i = 0; i < connections.length; i++) {
  81. var socket = connections[i];
  82. if (id === socket.id) {
  83. return socket;
  84. }
  85. }
  86. }