server.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. var app = require('express').createServer()
  2. , io = require('socket.io').listen(app);
  3. app.listen(80);
  4. app.get('/', function (req, res) {
  5. res.sendfile(__dirname + '/example/index.html');
  6. });
  7. app.get('/style.css', function (req, res) {
  8. res.sendfile(__dirname + '/example/style.css');
  9. });
  10. app.get('/io.js', function (req, res) {
  11. res.sendfile(__dirname + '/lib/io.js');
  12. });
  13. var connections = [];
  14. var colors = {};
  15. io.sockets.on('connection', function(socket) {
  16. console.log("connection received");
  17. connections.push(socket);
  18. colors[socket.id] = Math.floor(Math.random()* 0xFFFFFF)
  19. var connectionsId = [];
  20. for (var i = 0, len = connections.length; i < len; i++) {
  21. var id = connections[i].id;
  22. if (id !== socket.id) {
  23. connectionsId.push(id);
  24. }
  25. }
  26. socket.emit('get peers', {
  27. connections: connectionsId
  28. });
  29. socket.broadcast.emit('new peer connected', { socketId: socket.id });
  30. socket.on('disconnect', function() {
  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.emit('remove peer connected', { socketId: socket.id });
  37. }
  38. }
  39. });
  40. socket.on('receive ice candidate', function(data) {
  41. console.log("ice candidate received");
  42. var soc = getSocket(data.socketId);
  43. if (soc) {
  44. soc.emit('receive ice candidate', {
  45. label: data.label,
  46. candidate: data.candidate,
  47. socketId: socket.id
  48. });
  49. }
  50. });
  51. socket.on('send offer', function(data) {
  52. console.log("offer received");
  53. var soc = getSocket(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. console.log("answer received");
  63. var soc = getSocket(data.socketId);
  64. if (soc) {
  65. soc.emit('receive answer', {
  66. sdp: data.sdp,
  67. socketId: socket.id
  68. });
  69. }
  70. });
  71. socket.on('chat msg', function(msg) {
  72. console.log("chat received");
  73. socket.broadcast.emit('receive chat msg', { msg: msg, color: colors[socket.id]});
  74. });
  75. });
  76. function getSocket(id) {
  77. for (var i = 0; i < connections.length; i++) {
  78. var socket = connections[i];
  79. if (id === socket.id) {
  80. return socket;
  81. }
  82. }
  83. }