/js/lib/Socket.IO-node/lib/socket.io/transports/xhr-multipart.js

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs · JavaScript · 105 lines · 58 code · 18 blank · 29 comment · 10 complexity · 4340fc874d25f8034e1531bb69ed4b72 MD5 · raw file

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