Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io client ignoring port when namespace used [Bug?]

I have a simple node.js app with socket.io (1.3.5), taken from socket.io examples:

// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(__dirname + '/public'));

io.of('/admin').on('connection', function(socket){
    //handle conection on /admin namespace
});

io.of('/user').on('connection', function(socket){
    //handle conection on /user namespace
});

Now in my front-end I connect to these specific namespaces like so (again, taken from the example):

var admin_socket = io('/admin');
var user_socket = io('/user');

The app is running on port 3000 and the website is opened using URL localhost:3000.
When doing that I am getting CORS errors, it seems like Socket.io on client side is not auto-detecting the port number as soon as I start using namespaces (in firefox dev tools I can see requests going to localhost/ rather than localhost:3000/).


If on my server-side I don't use namespaces:

io.on('connection', function(socket){
    //handle general conection
});

And on front-end I connect this way:

var socket = io();

Everything works fine, port auto-discovery works and in firefox dev tools I can see connections being made to localhost:3000/.


Alternatively, if I still use namespaces on my back-end, and on front end I connect like so:

var admin_socket = io('localhost:3000/admin');
var user_socket = io(':3000/user');   //I can skip localhost

Again everything works (and indeed in firefox dev tools I can see network requests going to localhost:3000/).


How come the port auto-discovery is not working with namespaces? Is there a way to get it to work? Am I missing something here? Thanks.


See my answer below for a fix...

like image 218
Daniel Gruszczyk Avatar asked Mar 26 '15 23:03

Daniel Gruszczyk


1 Answers

Ok so I did some debugging of code in socket.io.js and realized there is a potential bug there. On line 1050 a loc.hostname is used instead of loc.host. This causes a hostname to be used when passing in a namespace, this doesn't include port number.
In case of no namespace being used, on line 1024 loc.host is being used and everything is fine.
I have taken a copy of the file and changed line 1050 to use host and everything works fine.
Found github issue with that, it is fixed in 1.4.x: https://github.com/Automattic/socket.io-client/issues/812

like image 75
Daniel Gruszczyk Avatar answered Oct 18 '22 20:10

Daniel Gruszczyk