peer.js 2.4 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. this._socket.onmessage = function(event) {
  25. var message = JSON.parse(event.data);
  26. var peer = message.src;
  27. var connection = self.connections[peer];
  28. switch (message.type) {
  29. case 'ID':
  30. self._id = message.id;
  31. self.emit('ready', self._id);
  32. break;
  33. case 'OFFER':
  34. var options = {
  35. metadata: message.metadata,
  36. peer: peer,
  37. id: self._id,
  38. originator: false,
  39. sdp: message.sdp
  40. };
  41. var connection = new DataConnection(options, self._socket, function(err, connection) {
  42. if (!err) {
  43. self.emit('connection', connection);
  44. }
  45. });
  46. self.connections[peer] = connection;
  47. break;
  48. case 'ANSWER':
  49. if (connection) connection.handleAnswer(message);
  50. break;
  51. case 'CANDIDATE':
  52. if (connection) connection.handleCandidate(message);
  53. break;
  54. case 'LEAVE':
  55. if (connection) connection.handleLeave(message);
  56. break;
  57. case 'PORT':
  58. if (browserisms && browserisms == 'Firefox') {
  59. connection.handlePort(message);
  60. break;
  61. }
  62. case 'DEFAULT':
  63. util.log('PEER: unrecognized message ', message.type);
  64. break;
  65. }
  66. };
  67. // Announce as a PEER to receive an ID.
  68. this._socket.send(JSON.stringify({
  69. type: 'PEER'
  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, this._socket, cb);
  81. this.connections[peer] = connection;
  82. };
  83. exports.Peer = Peer;