Socket.io-client: Using namespace will ignore port, or default to port 80

Created on 3 Feb 2015  路  56Comments  路  Source: socketio/socket.io-client

What's wrong:

I have the socket.io service running on port 4040 (for example), which exposes namespace /chat. From the client side, if I try to connect to the namespace without specifying the full url, the window url will be used without the port (or default to port 80).

What works:

From the client side, connecting to the default namespace is still okay, e.g. io.connect() or io() will correctly connect with the full url 192.168.0.149:4040. Needless to say the full url works.

Repro Code

# app.coffee
express = require 'express'
io = require 'socket.io'
http = require 'http'
app = express()
server = http.createServer(app)
io = io.listen server

server.listen 4040

app.use(express.static "#{__dirname}/public")

chat = io.of 'chat'

chat.on 'connection', (socket) ->
  socket.emit 'welcome', 'howdy'

# index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Chat with port demo</title>
  </head>
  <body>
    <h1>Chat ip demo</h1>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io('/chat');
      socket.once('welcome', function (message) {
        console.log(message);
      });
    </script>
  </body>
</html>

# package.json
{
  "name": "socdemo",
  "version": "1.0.0",
  "description": "",
  "main": "app.coffee",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.11.2",
    "socket.io": "^1.3.2"
  }
}

# error (misleading error since it's because there is nothing running on 192.168.0.149:80)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.0.149/socket.io/?EIO=3&transport=polling&t=1422967677888-0. This can be fixed by moving the resource to the same domain or enabling CORS.

Most helpful comment

Fixed in 1.4.x.

All 56 comments

This looks fixed by #803. Though not released yet.

This is not fixed yet. Now when trying to connect to a namespace on a different port than 80 you get the following error:

 GET http://localhost/socket.io/?EIO=3&transport=polling&t=1423870326340-9 net::ERR_CONNECTION_REFUSED
(index):24 Error connecting Error: xhr poll error {type: "TransportError", description: 0, stack: (...), message: "xhr poll error"}

Code to reproduce:
app.js:

var http = require('http'),
    fs = require('fs'),
    index = fs.readFileSync(__dirname + '/index.html');

    // Send index.html to all requests
    var app = http.createServer(function(req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(index);
    });

    // Socket.io server listens to our app
    var io = require('socket.io').listen(app);

    io.sockets.on('connection', function(socket) {
        console.log("Connected");
    });

    var auth = io.of('/test').use(function(socket, next){
        console.log("Authenticating...")
        next();
    }); 

    auth.on('connection', function(socket){
        console.log("Connected to namespace /test");
        socket.emit('welcome', { message: new Date().toJSON() });
        socket.on('i am client', console.log);
    })

    function sendTime() {
        io.of('/test').emit('time', { time: new Date().toJSON() });
    }

    setInterval(sendTime, 100);

app.listen(8088);

index.html:

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io.connect('http://localhost:8088/test', {
                timeout: 3000
            });

            socket.on('welcome', function(data) {
                document.getElementById("start").innerHTML = data.message
                socket.emit('i am client', {data: 'foo!'});
            });
            socket.on('time', function(data) {
                document.getElementById("end").innerHTML =  data.time;
            });
            socket.on('message', function() { console.log(arguments) });

            socket.on('error', function(err){
                console.log("Error:", err);
            })

            socket.on('connect_error', function(err){
                console.log("Error connecting", err);
            })
        </script>
    </head>
    <body>
        <p id='start'></p>
        <p id='end'></p>
    </body>
</html>

@manast I think this problem should happen only when using a relative path without a host. Do you mean there is another issue?

I don't know if it a different issue or a issue that is more complicated than initially expected. But if you test the code that I pasted above against master you will easily be able to reproduce. And by just changing the port to 80 it will work.

@manast I couldn't reproduce it. How did you install the source of master?

"socket.io": "Automattic/socket.io#a93d05a9f3f3b9697abc922163980f5788f9c6fb"

The above is my setting of package.json.

oh, ok sorry, you are right, the example code is working with current master. But if you change the line

var socket = io.connect('http://localhost:8088/test', {

to

var socket = io.connect('/test', {

then you will get the error that I reported above.

@manast I believe the error is because socket.io.js is old yet (no problem about that). If you'd like to try, you can make build to update it.

Seems like the original problem that I posted is still not fixed in 1.3.4.

@nlhkh yeah, it's not released yet.

The basic example on http://socket.io/docs/ fails on Chrome and Firefox when using a non-standard port such as 8000. The client tries to connect to the server, but omits the port.

Expected:
http://localhost:8000/socket.io/?EIO=3&transport=polling&t=1424145292759-2

Actual:
http://localhost/socket.io/?EIO=3&transport=polling&t=1424145292759-2

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/socket.io/?EIO=3&transport=polling&t=1424145292759-2. This can be fixed by moving the resource to the same domain or enabling CORS.

var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(8000);

function handler (req, res) {
    fs.readFile(__dirname + '/index.html',
    function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        }
        res.writeHead(200);
        res.end(data);
    });
}

io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
});

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

The example works as early as socket.[email protected]. Something happened between 1.3.1 and 1.3.2.

I'm facing exactly the same problem as user invisibleroads. When I switch to the default namespace it works, also with a different port than 80. As soon as there are namespaces in use, the CORS error comes up...

I also encountered this problem when debugging socket connection for webpack-dev-server.

I've tried to follow the modification in this fix and it worked for me :)
The commit was merged but is not published yet.

Note: in the fix loc.hostname does not contain port, but loc.host does. This is what does the trick.

I can reproduce the problem. In fact I even described it on stackoverflow before finding the issue here:
http://stackoverflow.com/questions/29290563/socket-io-client-ignoring-port-when-namespace-used-bug
I can see this was merged in, when will this be released? For now it stops me from using npm package for socket.io-client, and use my own local modified copy.

+1

This was fixed in 5abd97b2313aa3e9c9b2e1035dd4c24379fd77e8, but somehow didn't make it into socket.io.js.
I guess someone forgot to run make before publishing a new version?

It has been a month the since last patch version was published. I think it's high time to release a new patch version that includes this fix?

+1

:+1:

:+1:

:+1:

Still facing this issue in 1.3.5...

I'm manually update the socket.io.js file as per the fix here: https://github.com/Automattic/socket.io-client/commit/5abd97b2313aa3e9c9b2e1035dd4c24379fd77e8 , for now.

+1

:+1:

+1

How soon will the new version :question:

@rauchg Is it possible to release a new version to fix this ?

+1

:+1:

We're still stuck on 1.3.1 because of this bug. @rauchg, any updates on when the next version is coming?

@pacarole: while this is annoying, "being stuck" seems to be an overstatement considering the easy workaround

We are still stuck at 1.2.1, and have been trying to upgrade to 1.3.x for half a year :P Feels funny that this kind of fundamental bug has not been solved even though new releases has come out since then. I really hope that there are no serious security issues found in 1.2.1 before this is fixed ;)

For everyone, here's a quick fix by @ahmetemir https://github.com/Automattic/socket.io/issues/2025#issuecomment-76386655

Add something like {port:3000} as option, eg:
Not window.socket = io.connect('vagrant:30002/tty/test'); but window.socket = io.connect('vagrant:30002/tty/test', {port:30002} );

This _WORKS_ for me (_/蠅锛糭)

I'm still having this issue.

I just ran into this. My work-around is thus:

var socket = io.connect(window.location.origin + '/namespace');

:see_no_evil:

@bugeats This workaround is working. Yet unfortunate.

+1

@bugeats has right answer, should be closed now

@iamwave007, no it should not. @bugeats only described a workaround but the problem should be fixed inside of the library.

I totally agree with @JustBlackBird :-)

It looks like the fix has already been applied to lib/url.js. (8 months ago??? 5abd97b2313aa3e9c9b2e1035dd4c24379fd77e8)
Yet, the fix still hasn't been applied to the bundled socket.io.js

This bug has been impacting me as well.

As @invisibleroads said, it was working in 1.3.1 (and in 1.2.0 from my personal experience).
It has be broken again in 1.3.2.

This issue looks like a ghost haunting socket.io client over and over again, 'til end of time.
Someone has to lift the curse ;-).

+1

+1

+1

+1

+1

+1

@yamsellem lifting the curse atm

+1

@rauchg, @nkzawa is there any progress on this?

Those +1 posts are extremely annoying, as they contribute nothing to the discussion and everbody who subscribed the topic gets flooded with useless emails.

Sorry, but had to say that. Now you can delete the email that was triggered by this post :)

@deefens I guess the +1 is a simple way to subscribe to the topic (_I used it that way before_).
_There is a better way_: a 'notifications' label at the top of the issue with a 'subscribe' button ;-).

@yamsellem it's not only a way to subscribe but also a way to show maintainers how many people face the problem.

Fixed in 1.4.x.

Was this page helpful?
0 / 5 - 0 ratings