peer.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. };
  16. util.inherits(Peer, EventEmitter);
  17. /** Start up websocket communications. */
  18. Peer.prototype._socketInit = function() {
  19. var self = this;
  20. this._socket.onmessage = function(event) {
  21. var message = JSON.parse(event.data);
  22. var peer = message.src;
  23. var connection = self.connections[peer];
  24. switch (message.type) {
  25. case 'ID':
  26. self._id = message.id;
  27. self.emit('ready', self._id);
  28. break;
  29. case 'OFFER':
  30. var options = {
  31. metadata: message.metadata,
  32. sdp: message.sdp
  33. };
  34. var connection = new DataConnection(self._id, peer, self._socket, function(err, connection) {
  35. if (!err) {
  36. self.emit('connection', connection);
  37. }
  38. }, options);
  39. self.connections[peer] = connection;
  40. break;
  41. case 'ANSWER':
  42. if (connection) connection.handleSDP(message);
  43. break;
  44. case 'CANDIDATE':
  45. if (connection) connection.handleCandidate(message);
  46. break;
  47. case 'LEAVE':
  48. if (connection) connection.handleLeave(message);
  49. break;
  50. case 'PORT':
  51. if (browserisms == 'Firefox') {
  52. connection.handlePort(message);
  53. break;
  54. }
  55. case 'DEFAULT':
  56. util.log('PEER: unrecognized message ', message.type);
  57. break;
  58. }
  59. };
  60. this._socket.onopen = function() {
  61. // Announce as a PEER to receive an ID.
  62. self._socket.send(JSON.stringify({
  63. type: 'PEER'
  64. }));
  65. };
  66. };
  67. Peer.prototype.connect = function(peer, metadata, cb) {
  68. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  69. var options = {
  70. metadata: metadata
  71. };
  72. var connection = new DataConnection(this._id, peer, this._socket, cb, options);
  73. this.connections[peer] = connection;
  74. };
  75. exports.Peer = Peer;