bullet.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // WebSocket Transport
  2. $ws = { heart: true, interval: 4000,
  3. creator: function(url) { return window.WebSocket ? new window.WebSocket(url) : false; },
  4. onheartbeat: function() { // this.channel.send('PING');
  5. } };
  6. // N2O Reliable Connection
  7. $conn = { onopen: nop, onmessage: nop, onclose: nop, onconnect: nop,
  8. send: function(data) { if (this.port.channel) this.port.channel.send(data); },
  9. close: function() { if (this.port.channel) this.port.channel.close(); } };
  10. ct = 0;
  11. transports = [ $ws ];
  12. heartbeat = null;
  13. reconnectDelay = 1000;
  14. maxReconnects = 100;
  15. function nop() { }
  16. function bullet(url) { $conn.url = url; return $conn; }
  17. function xport() { return maxReconnects <= ct ? false : transports[ct++ % transports.length]; }
  18. function reconnect() { setTimeout(function() { connect(); }, reconnectDelay); }
  19. function next() { $conn.port = xport(); return $conn.port ? connect() : false; }
  20. function connect() {
  21. $conn.port.channel = $conn.port.creator($conn.url);
  22. if (!$conn.port.channel) return next();
  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; }