bullet.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // WebSocket Transport
  2. $ws = { heart: true, interval: 5000,
  3. creator: function(url) { return window.WebSocket ? new window.WebSocket(url) : false; },
  4. onheartbeat: function() { this.channel.send('PING'); } };
  5. // N2O Reliable Connection
  6. $conn = { onopen: nop, onmessage: nop, onclose: nop, onconnect: nop,
  7. send: function(data) { if (this.port.channel) this.port.channel.send(data); },
  8. close: function() { if (this.port.channel) this.port.channel.close(); } };
  9. ct = 0;
  10. transports = [ $ws ];
  11. heartbeat = null;
  12. reconnectDelay = 1000;
  13. maxReconnects = 100;
  14. function nop() { }
  15. function bullet(url) { $conn.url = url; return $conn; }
  16. function xport() { return maxReconnects <= ct ? false : transports[ct++ % transports.length]; }
  17. function reconnect() { setTimeout(function() { connect(); }, reconnectDelay); }
  18. function next() { $conn.port = xport(); return $conn.port ? connect() : false; }
  19. function connect() {
  20. $conn.port.channel = $conn.port.creator($conn.url);
  21. if (!$conn.port.channel) return next();
  22. $conn.port.channel.binaryType = "arraybuffer";
  23. $conn.port.channel.onmessage = function(e) { $conn.onmessage(e); };
  24. $conn.port.channel.onopen = function() {
  25. if ($conn.port.heart) heartbeat = setInterval(function(){$conn.port.onheartbeat();}, $conn.port.interval);
  26. $conn.onopen();
  27. $conn.onconnect(); };
  28. $conn.port.channel.onclose = function() { $conn.onclose(); clearInterval(heartbeat); reconnect(); };
  29. return $conn; }