jsonp-polling.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*!
  2. * socket.io-node
  3. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module requirements.
  8. */
  9. var HTTPPolling = require('./http-polling');
  10. var jsonpolling_re = /^\d+$/
  11. /**
  12. * Export the constructor.
  13. */
  14. exports = module.exports = JSONPPolling;
  15. /**
  16. * JSON-P polling transport.
  17. *
  18. * @api public
  19. */
  20. function JSONPPolling (mng, data, req) {
  21. HTTPPolling.call(this, mng, data, req);
  22. this.head = 'io.j[0](';
  23. this.foot = ');';
  24. if (data.query.i && jsonpolling_re.test(data.query.i)) {
  25. this.head = 'io.j[' + data.query.i + '](';
  26. }
  27. };
  28. /**
  29. * Inherits from Transport.
  30. */
  31. JSONPPolling.prototype.__proto__ = HTTPPolling.prototype;
  32. /**
  33. * Transport name
  34. *
  35. * @api public
  36. */
  37. JSONPPolling.prototype.name = 'jsonppolling';
  38. /**
  39. * Make sure POST are decoded.
  40. */
  41. JSONPPolling.prototype.postEncoded = true;
  42. /**
  43. * Handles incoming data.
  44. * Due to a bug in \n handling by browsers, we expect a JSONified string.
  45. *
  46. * @api private
  47. */
  48. JSONPPolling.prototype.onData = function (data) {
  49. try {
  50. data = JSON.parse(data);
  51. } catch (e) {
  52. this.error('parse', 'reconnect');
  53. return;
  54. }
  55. HTTPPolling.prototype.onData.call(this, data);
  56. };
  57. /**
  58. * Performs the write.
  59. *
  60. * @api private
  61. */
  62. JSONPPolling.prototype.doWrite = function (data) {
  63. HTTPPolling.prototype.doWrite.call(this);
  64. var data = data === undefined
  65. ? '' : this.head + JSON.stringify(data) + this.foot;
  66. this.response.writeHead(200, {
  67. 'Content-Type': 'text/javascript; charset=UTF-8'
  68. , 'Content-Length': Buffer.byteLength(data)
  69. , 'Connection': 'Keep-Alive'
  70. , 'X-XSS-Protection': '0'
  71. });
  72. this.response.write(data);
  73. this.log.debug(this.name + ' writing', data);
  74. };