/js/lib/Socket.IO-node/lib/socket.io/transports/xhr-multipart.js
JavaScript | 105 lines | 58 code | 18 blank | 29 comment | 10 complexity | 4340fc874d25f8034e1531bb69ed4b72 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause
1 2/*! 3 * Socket.IO - transports - Multipart 4 * Copyright (c) 2010-2011 Guillermo Rauch <guillermo@learnboost.com> 5 * MIT Licensed 6 */ 7 8var Client = require('../client') 9 , qs = require('querystring'); 10 11/** 12 * Expose `Multipart`. 13 */ 14 15module.exports = Multipart; 16 17/** 18 * Initialize a `Multipart` client. 19 * 20 * @api private 21 */ 22 23function Multipart() { 24 Client.apply(this, arguments); 25}; 26 27/** 28 * Inherit from `Client.prototype`. 29 */ 30 31Multipart.prototype.__proto__ = Client.prototype; 32 33/** 34 * Connection implementation. 35 * 36 * @api private 37 */ 38 39Multipart.prototype._onConnect = function(req, res){ 40 var self = this 41 , body = ''; 42 43 // https://developer.mozilla.org/En/HTTP_Access_Control 44 if (req.headers.origin && this._verifyOrigin(req.headers.origin)){ 45 res.setHeader('Access-Control-Allow-Origin', '*'); 46 res.setHeader('Access-Control-Allow-Credentials', 'true'); 47 } 48 49 if (typeof req.headers['access-control-request-method'] !== 'undefined'){ 50 // CORS preflight message 51 res.setHeader('Access-Control-Allow-Methods', req.headers['access-control-request-method']); 52 res.end('ok'); 53 return; 54 } 55 56 switch (req.method){ 57 case 'GET': 58 Client.prototype._onConnect.call(this, req, res); 59 res.setHeader('Content-Type', 'multipart/x-mixed-replace;boundary="socketio"'); 60 res.setHeader('Connection', 'keep-alive'); 61 req.connection.on('end', function(){ self._onClose(); }); 62 res.useChunkedEncodingByDefault = false; 63 res.shouldKeepAlive = true; 64 res.write("--socketio\n"); 65 if ('flush' in res) res.flush(); 66 this._payload(); 67 break; 68 69 case 'POST': 70 res.setHeader('Content-Type', 'text/plain'); 71 req.on('data', function(chunk){ body += chunk }); 72 req.on('end', function(){ 73 try { 74 var msg = qs.parse(body); 75 self._onMessage(msg.data); 76 } catch(e){ 77 self.listener.log('xhr-multipart message handler error - ' + e.stack); 78 } 79 res.end('ok'); 80 body = ''; 81 }); 82 break; 83 } 84}; 85 86/** 87 * Write implementation. 88 * 89 * @param {String} message 90 * @api private 91 */ 92 93Multipart.prototype._write = function(message){ 94 if (this._open){ 95 var res = this.response 96 , charset = ''; 97 98 if (1 == message.length && 6 == message.charCodeAt(0)) 99 charset = '; charset=us-ascii'; 100 101 res.write("Content-Type: text/plain" + charset + "\n\n"); 102 res.write(message + "\n"); 103 res.write("--socketio\n"); 104 } 105};