peer.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. peer: 'ws://localhost'
  7. }, options);
  8. this.options = options;
  9. util.debug = options.debug;
  10. this._id = null;
  11. this._socket = new WebSocket(options.ws);
  12. this._socketInit();
  13. // Connections
  14. this.connections = {};
  15. // Queued connections to make
  16. this._queued = [];
  17. };
  18. util.inherits(Peer, EventEmitter);
  19. /** Start up websocket communications. */
  20. Peer.prototype._socketInit = function() {
  21. var self = this;
  22. this._socket.onmessage = function(event) {
  23. var message = JSON.parse(event.data);
  24. var peer = message.src;
  25. var connection = self.connections[peer];
  26. switch (message.type) {
  27. case 'ID':
  28. self._id = message.id;
  29. self._processQueue();
  30. self.emit('ready', self._id);
  31. break;
  32. case 'OFFER':
  33. var options = {
  34. metadata: message.metadata,
  35. sdp: message.sdp
  36. };
  37. var connection = new DataConnection(self._id, peer, self._socket, function(err, connection) {
  38. if (!err) {
  39. self.emit('connection', connection, metadata);
  40. }
  41. }, options);
  42. self.connections[peer] = connection;
  43. break;
  44. case 'ANSWER':
  45. if (connection) connection.handleSDP(message);
  46. break;
  47. case 'CANDIDATE':
  48. if (connection) connection.handleCandidate(message);
  49. break;
  50. case 'LEAVE':
  51. if (connection) connection.handleLeave(message);
  52. break;
  53. case 'PORT':
  54. if (browserisms == 'Firefox') {
  55. connection.handlePort(message);
  56. break;
  57. }
  58. case 'DEFAULT':
  59. util.log('PEER: unrecognized message ', message.type);
  60. break;
  61. }
  62. };
  63. this._socket.onopen = function() {
  64. // Announce as a PEER to receive an ID.
  65. self._socket.send(JSON.stringify({
  66. type: 'PEER'
  67. }));
  68. };
  69. };
  70. Peer.prototype._processQueue = function() {
  71. while (this._queued.length > 0) {
  72. var cdata = this._queued.pop();
  73. this.connect.apply(this, cdata);
  74. }
  75. };
  76. Peer.prototype.connect = function(peer, metadata, cb) {
  77. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  78. if (!this._id) {
  79. this._queued.push(Array.prototype.slice.apply(arguments));
  80. return;
  81. }
  82. var options = {
  83. metadata: metadata
  84. };
  85. var connection = new DataConnection(this._id, peer, this._socket, cb, options);
  86. this.connections[peer] = connection;
  87. };
  88. exports.Peer = Peer;