socket.io-client icon indicating copy to clipboard operation
socket.io-client copied to clipboard

Using namespace will ignore port, or default to port 80

Open khanetor opened this issue 11 years ago • 56 comments

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.

khanetor avatar Feb 03 '15 12:02 khanetor

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

nkzawa avatar Feb 03 '15 18:02 nkzawa

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 avatar Feb 13 '15 23:02 manast

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

nkzawa avatar Feb 14 '15 14:02 nkzawa

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 avatar Feb 15 '15 10:02 manast

@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.

nkzawa avatar Feb 15 '15 16:02 nkzawa

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 avatar Feb 15 '15 18:02 manast

@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.

nkzawa avatar Feb 16 '15 03:02 nkzawa

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

khanetor avatar Feb 16 '15 16:02 khanetor

@nlhkh yeah, it's not released yet.

nkzawa avatar Feb 16 '15 16:02 nkzawa

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>

invisibleroads avatar Feb 17 '15 04:02 invisibleroads

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

invisibleroads avatar Feb 17 '15 13:02 invisibleroads

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...

deefens avatar Mar 11 '15 08:03 deefens

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.

MrOrz avatar Mar 21 '15 07:03 MrOrz

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.

codan84 avatar Mar 27 '15 08:03 codan84

+1

manast avatar Mar 27 '15 10:03 manast

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?

amiuhle avatar Apr 01 '15 09:04 amiuhle

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?

MrOrz avatar Apr 05 '15 09:04 MrOrz

+1

neemah avatar Apr 06 '15 09:04 neemah

:+1:

JustBlackBird avatar Apr 06 '15 12:04 JustBlackBird

:+1:

ruhenheim avatar Apr 06 '15 12:04 ruhenheim