server.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var express = require('express');
  2. var fs = require('fs');
  3. var app = express.createServer();
  4. var io = require('socket.io').listen(app);
  5. // Initialize main server.
  6. app.use(express.bodyParser());
  7. app.use(express.static(__dirname + '/public'));
  8. app.set('view engine', 'ejs');
  9. app.set('views', __dirname + '/views');
  10. // P2P sources: { socket id => url }.
  11. sources = {};
  12. // socket.io clients.
  13. clients = {};
  14. // P2Ps. { source id => group members }
  15. connections = {};
  16. // For connecting clients:
  17. // Src will connect upon creating a link.
  18. // Receivers will connect after clicking a button and entering an optional key.
  19. io.sockets.on('connection', function(socket) {
  20. clients[socket.id] = socket;
  21. // Source connected.
  22. socket.on('source', function(msg, fn) {
  23. fn({ 'id': socket.id });
  24. connections(socket.id) = [];
  25. });
  26. // Sink connected.
  27. socket.on('sink', function(msg, fn) {
  28. var source_id = msg.source;
  29. var sink_id = socket.id;
  30. var source = clients[source_id];
  31. source.emit('sink-connected', { 'sink': sink_id });
  32. fn({ 'id': sink_id });
  33. });
  34. // Offer from src to dest.
  35. socket.on('offer', function (msg) {
  36. sink = clients[msg.sink];
  37. sink.emit('offer', msg);
  38. });
  39. // Answer from dest to src.
  40. socket.on('answer', function (msg) {
  41. source = msg.source;
  42. source.emit('answer', msg, function() {
  43. // Add to list of successful connections.
  44. connections[msg.source].append(msg.sink);
  45. console.log('Successful Offer/Answer between ', msg.source, ' and ', msg.sink);
  46. });
  47. });
  48. socket.on('disconnect', function() {
  49. // Handle on client side?
  50. socket.broadcast.to(connections[socket.id]).emit('Host disconnected');
  51. delete connections[socket.id];
  52. delete clients[socket.id];
  53. });
  54. });
  55. app.get('/', function(req, res){
  56. res.render('index');
  57. });
  58. app.listen(80);