Skip to content

Instantly share code, notes, and snippets.

@epadillas
Created July 14, 2013 10:26
Show Gist options
  • Select an option

  • Save epadillas/5993856 to your computer and use it in GitHub Desktop.

Select an option

Save epadillas/5993856 to your computer and use it in GitHub Desktop.

Revisions

  1. epadillas created this gist Jul 14, 2013.
    47 changes: 47 additions & 0 deletions client.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    // Send cookies for the socket.io handshake (sails.js)
    // Based on https://gist.github.com/jfromaniello/4087861
    // Socket.io open ticket (started by jfromaniello):
    // https://github.com/LearnBoost/socket.io-client/pull/512

    var io = require('socket.io-client');
    var request = require('request');
    var xhr = require('socket.io-client/node_modules/xmlhttprequest');
    var xhrOriginal = require('xmlhttprequest');

    var myUrl = 'http://192.168.56.101:1337';
    var cookieJar = request.jar();

    // From socket.io-client's module 'xmlhttprequest', rewrie its XMLHttpRequest function.
    xhr.XMLHttpRequest = function() {
    this.XMLHttpRequest = xhrOriginal.XMLHttpRequest;
    xhrOriginal.XMLHttpRequest.apply(this, arguments);
    this.setDisableHeaderCheck(true); // Allow header modifications.

    // Rewrite the 'open' function.
    var openOriginal = this.open;
    this.open = function(method, url, async, user, password) {
    openOriginal.apply(this, arguments);
    var header = cookieJar.get({url: myUrl}).map(function(cookie) {
    return cookie.name + '=' + cookie.value;
    }).join('; ');
    this.setRequestHeader('cookie', header);
    };
    };

    // Send the cookie first before attempting to connect via socket-io,
    // thus, avoiding the handshake error.
    request.post({jar: cookieJar, url: myUrl}, function(err, resp, body) {
    var socket = io.connect(myUrl);
    socket.on('connecting', function() {
    console.log('(II) Connecting to server');
    });
    socket.on('connect', function() {
    console.log('(II) Successfully connected to server');
    });
    socket.on('error', function(reason) {
    console.log('(EE) Error connecting to server: ' + reason);
    });
    socket.on('disconnect', function(reason) {
    console.log('(II) Disconnected from server\n');
    });
    });