4 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
12 var HTTPPolling = require('./http-polling');
13 var jsonpolling_re = /^\d+$/
16 * Export the constructor.
19 exports = module.exports = JSONPPolling;
22 * JSON-P polling transport.
27 function JSONPPolling (mng, data, req) {
28 HTTPPolling.call(this, mng, data, req);
30 this.head = 'io.j[0](';
33 if (data.query.i && jsonpolling_re.test(data.query.i)) {
34 this.head = 'io.j[' + data.query.i + '](';
39 * Inherits from Transport.
42 JSONPPolling.prototype.__proto__ = HTTPPolling.prototype;
50 JSONPPolling.prototype.name = 'jsonppolling';
53 * Make sure POST are decoded.
56 JSONPPolling.prototype.postEncoded = true;
59 * Handles incoming data.
60 * Due to a bug in \n handling by browsers, we expect a JSONified string.
65 JSONPPolling.prototype.onData = function (data) {
67 data = JSON.parse(data);
69 this.error('parse', 'reconnect');
73 HTTPPolling.prototype.onData.call(this, data);
82 JSONPPolling.prototype.doWrite = function (data) {
83 HTTPPolling.prototype.doWrite.call(this);
85 var data = data === undefined
86 ? '' : this.head + JSON.stringify(data) + this.foot;
88 this.response.writeHead(200, {
89 'Content-Type': 'text/javascript; charset=UTF-8'
90 , 'Content-Length': Buffer.byteLength(data)
91 , 'Connection': 'Keep-Alive'
92 , 'X-XSS-Protection': '0'
95 this.response.write(data);
96 this.log.debug(this.name + ' writing', data);