Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Socket.io 'Cannot connect'. Client on different domain/port

Socket.io 'Cannot connect'. Client on different domain/port

Problem

I'm having trouble connecting to socket.io with the client being located on a different port, on the same machine.

The client is part of a site run on Apache (port 80) and Nodejs is being run on 8585.

Any idea what I'm doing wrong here?

On the client side, I get the 'Unable to connect Socket.IO' message, with no reason.

Server:

var express       = require('express'),
    connect       = require('connect'),
    RedisStore    = require('connect-redis')(express),
    io            = require('socket.io').listen(app),
    routes        = require('./routes'),
    request       = require('request');

var app = module.exports = express.createServer();

// Configuration
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: "secret", store: new RedisStore}));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

io.set('authorization', function(handshakeData, callback) {
    console.log('authorization');
    callback(null, true);
});

//Socket IO connection
io.sockets.on('connection', function (socket) {
    var session = socket.handshake.session;
    console.log(session);
});

app.listen(8585);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Client: (run from a site on apache and different domain, but same server).

    var sio = io.connect('http://localhost:8585');

    sio.socket.on('error', function (reason){
        console.error('Unable to connect Socket.IO', reason);
    });

    sio.on('connect', function (){
        console.error('successfully established a working connection \o/');
    });

Thank you!

Problem courtesy of: dzm

Solution

Unless you're running the browser on the same computer as the server, "localhost" in your code will refer to the computer running the browser, not the server. DNS lookups for localhost always resolve to the computer doing the lookup. And even if you're accessing the site on the same computer as the server, unless you're accessing it as "localhost", the browser's security policies will prevent you from talking to localhost.

Solution courtesy of: Chuck

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Socket.io 'Cannot connect'. Client on different domain/port

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×