server.js 2.3 KB

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