peer.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. function Peer(options) {
  2. if (!(this instanceof Peer)) return new Peer(options);
  3. EventEmitter.call(this);
  4. options = util.extend({
  5. debug: false,
  6. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  7. ws: 'ws://localhost'
  8. }, options);
  9. util.debug = options.debug;
  10. this._id = null;
  11. // Connections
  12. this.connections = {};
  13. this._socket = new WebSocket(options.ws);
  14. // Init socket msg handlers
  15. var self = this;
  16. this._socket.onopen = function() {
  17. self.socketInit();
  18. };
  19. };
  20. util.inherits(Peer, EventEmitter);
  21. /** Start up websocket communications. */
  22. Peer.prototype.socketInit = function() {
  23. var self = this;
  24. // Announce as a PEER to receive an ID.
  25. this._socket.send(JSON.stringify({
  26. type: 'PEER'
  27. }));
  28. this._socket.onmessage = function(event) {
  29. var message = JSON.parse(event.data);
  30. var peer = message.src;
  31. var connection = self.connections[peer];
  32. switch (message.type) {
  33. case 'ID':
  34. self._id = message.id;
  35. self.emit('ready', self._id);
  36. break;
  37. case 'OFFER':
  38. var options = {
  39. metadata: message.metadata,
  40. peer: peer,
  41. id: self._id,
  42. originator: false,
  43. sdp: message.sdp
  44. };
  45. var connection = new DataConnection(options, socket, function(err, connection) {
  46. if (!err) {
  47. self.emit('connection', connection);
  48. }
  49. });
  50. self.connections[peer] = connection;
  51. break;
  52. case 'ANSWER':
  53. if (connection) connection.handleAnswer(message);
  54. break;
  55. case 'CANDIDATE':
  56. if (connection) connection.handleCandidate(message);
  57. break;
  58. case 'LEAVE':
  59. if (connection) connection.handleLeave(message);
  60. break;
  61. case 'PORT':
  62. if (browserisms && browserisms == 'Firefox') {
  63. connection.handlePort(message);
  64. break;
  65. }
  66. case 'DEFAULT':
  67. util.log('PEER: unrecognized message ', message.type);
  68. break;
  69. }
  70. };
  71. };
  72. Peer.prototype.connect = function(peer, metadata, cb) {
  73. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  74. var options = {
  75. metadata: metadata,
  76. id: this._id,
  77. peer: peer,
  78. originator: true
  79. };
  80. var connection = new DataConnection(options, socket, cb);
  81. this.connections[peer] = connection;
  82. };
  83. exports.Peer = Peer;