Socket.io: I can't connec to host in v1.0.X

Created on 30 May 2014  路  18Comments  路  Source: socketio/socket.io

Y have a problem in connection versi贸n 1.0 that I dont had in the versi贸n 0.9.X.

I have Django running in http://app.myhost.com and my node server in http://live.myhost.com:8001

Before I could connect me to the socket.io server v0.9.x like:
Client:
io.connect(//live.myhost.com:8001);
server:
io = require('socket.io')(port)
io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);

but now I have a problem (not taking the live url correctly):
GET http://app.myhost.com:8000/socket.io/?EIO=2&transport=polling&t=1401468282894-1 404 (NOT FOUND)

if I rewrite (io.connect(http://live.myhost.com:8001)) now have a new problem:
XMLHttpRequest cannot load http://live.myhost.com:8001/socket.io/?EIO=2&transport=polling&t=1401468608168-1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://app.myhost.com' is therefore not allowed access.

in debug mode to socket.io I have more info:
engine:core intercepting request for path "/socket.io/" +0ms
engine handling "GET" http request "/socket.io/?EIO=2&transport=polling&t=1401470024479-48" +0ms
engine unknown transport "polling" +3ms

Most helpful comment

Based on some testing, it appears there is a problem with the error handling middleware that is treating socketio connections as 404. A succesful app.js that doesn't trigger this error looks like this:

var express = require('express');
var http = require('http');
var path = require('path');
var socketio = require('socket.io');

var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var socket = require('./routes/socket');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

var server = http.Server(app);
var io = socketio.listen(server);
var port = process.env.PORT || 8080;

server.listen(port, function(){
  console.log("Express server listening on port " + port);
});

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

All 18 comments

i had the same problem, and found that you need to pass : in the ur for 1.0 to workl, where for 0.9 you pass host and port in options.

I do not understand what you say yuryb. Might you explain me with an example or on it, thanks.

Same problem .. :(

I also stumbled into this problem w/ Express 4 (mac osx, chrome). I used express-generator to create the app and have some suspicion that it may have to do with a) the boilerplate middleware, b) browserify, 3) me not knowing enough about websockets. I am almost certain this is something to do with port addr between Expresss app.listen and http server.listen and clientside io.connect.

var express = require('express');
var http = require('http');
var socketio = require('socket.io');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var socket = require('./routes/socket');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

var server = http.createServer(app);
var port = process.env.PORT || 8080;

server.listen(port, function(){
  console.log("Express server listening on port " + port);
});

var io = socketio.listen(server);

io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);

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

module.exports = app;

and then for main.js (clienside)

var App = function(page, io){

  var socket = io.connect('http://localhost:3000');

  socket.on('news', function(data){
    console.log(data);
    socket.emit('my other event', {
      my: 'data'
    });
  });
};
// Document Ready
document.addEventListener('DOMContentLoaded', function(){
  var io = require('socket.io-client');
  var app = new App(io);
});

If it helps any, here are the headers of the request/response

Request:

GET /socket.io/?EIO=2&transport=polling&t=1404667620992-68 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Accept: */*
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,da;q=0.6
Cookie: io=g-knpi1IeCCVOmfyAAAC

Query String Params
EIO=2&transport=polling&t=1404667620992-68

Response:

HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 1094
ETag: "-1293544181"
Date: Sun, 06 Jul 2014 17:27:00 GMT
Connection: keep-alive

Based on some testing, it appears there is a problem with the error handling middleware that is treating socketio connections as 404. A succesful app.js that doesn't trigger this error looks like this:

var express = require('express');
var http = require('http');
var path = require('path');
var socketio = require('socket.io');

var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var socket = require('./routes/socket');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

var server = http.Server(app);
var io = socketio.listen(server);
var port = process.env.PORT || 8080;

server.listen(port, function(){
  console.log("Express server listening on port " + port);
});

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

One difference between the two is the successful one you are calling var io = socketio.listen(server); before server.listen. Does changing the unsuccessful one's order of that call make it work?

Another difference is that in your failing app you have

io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);

but you do not have that in your successful app. Perhaps that is what is causing the issue?

@dougwilson Interesting, yes, removing io.set seems to fix it. It is strange though because I only added that line after doing some research after encountering this issue, where adding that line was a suggested solution, which leads me to believe it may have been a combination of things.

I was trying all sorts of different things in combination at some point, eventually I must have brute-forced myself into success, minus that io.set line. The docs seem to show that io.set/io.get have been replaced by io.use as well.

In regards to the position of socket.io.listen(server) vs server.listen, rearranging the order did not seem to have any particular effect. I actually had tried changing the order of operations a few times as well

OK. I looked through the socket.io code and didn't think re-ordering would be the answer, but was just pointing out a difference; socket.io will actually handle everything long before requests to it will even reach express, so I just knew it wasn't something going on in your express setup itself, based on how socket.io functions. Good to know it was that io.set line. I can only assume that it is turning off things, thus stuff is falling through to express app when you have that line.

Definitely a good call! Thanks for taking a look into it. Unfortunately I am very late on the socket.io bandwagon so it's all new to me :-)

an getting the same error. But I am not using any io.set calls.

In my situation, I have one file, app.js, where I setup Express 4 stuff and define routes, etc.

var express = require( "express" );
var app = express();
...

modules.export app;
Then I have another file serialListener.js, where I use sockets to communicate data retrieved from an Arduino to the web client.

module.exports = serialListener;

var app = require('./app');

var http = require('http');
var httpServer = http.createServer();
var io = require('socket.io').listen(http);
httpServer.listen(3001);
...

DIserialPort.on('data', function(data) {
receivedData += data.toString();
io.emit('update', {
dataSource: receivedData,
dataInputData: receivedData
});
});
When starting up node via $ node ./bin/www

I get these same socket.io errors GET /socket.io/?EIO.... 404

Is it an ordering proboem with my http listen?

I have tried many permutations of the io require and listen as per the socket.io threads here. But nothing works!

Please help. david

@davidwkleber Try replacing

var http = require('http');
var httpServer = http.createServer();
var io = require('socket.io').listen(http);
httpServer.listen(3001);

with

var http = require('http');
var httpServer = http.createServer(app);
var io = require('socket.io').listen(httpServer);
httpServer.listen(3001);
//var newrelic = require('newrelic');
var express = require('express');
var request = require('request');
var path = require('path');
var bodyParser = require('body-parser');

var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var port = process.env.PORT || 3000;
var parUrl = 'http://192.168.199.120/mohoo-telecom-activity-4/web';

app.set('views','../html');
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'../html')));

app.get('/ac4',function(req,res){
    console.log('requesting');
    res.render('begin');
});

//testing
io.on('connection',function(socket){
    console.log('a user gameover');

    socket.on('gameover',function(msg){
        console.log(msg);
        request('http://192.168.199.200/mohoo-telecom-activity-4/web/v1/user/get', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body);
            } else {
                console.log('false');
            }
        });
    })
});

http.listen(port,function(){
    console.log('listening on *:3000'+__dirname);
});

This is my code.
use 'app.listen(port);' causes 404 error.

This is ok

http.listen(port,function(){
    console.log('listening on *:3000'+__dirname);
});

like this is ok
The error with port addr between app.listen and http server.listen and clientside io.connect.
Use http.listen,the client does not appear 404 error but app.listen.

I am a chinese,English is very bad.

That works for me! THANKS! @vendetta0114

bin/www

#!/usr/bin/env node
var debug = require('debug')('app:www');
var app = require('../app');

var socketer = require('../lib/socket');

app.set('port', process.env.PORT || 3080);

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

socketer.boot(server);

/lib/socket.js

'use strict';

var socketio = require('socket.io');
var io;

function someFunction (server) {
  io = socketio.listen(server);
  io.on('connection', function (socket) { 
  });
}

exports.boot = someFunction;

This worked for me

require('socket.io')(somemagicvar)... is undebuggable because you have 20 magic vars.

socket.foo(x)
or io.on(data, (socket) => socket.on('foo', bar)
or socket(foo)(bar).connection(baz, (x) => socket.on(bar, foo))
?

this is undebuggable and unintelligable to me. humbley, please pick one paradigm.

eio.connect('localhost:8080') // 404 + XCORS error ... XCORS is undebugabble...

why the app cant find its own route at/magical-shit/tooth-fairy?polling=1&eio=3 is beyond me.

thumbs down.

socket was beautiful at 1.0, death by complexity. partially XCors fault imo.

using client side: io.connect('localhost:port') worked for me.

it should be ws://url or name:port

also i had to DL the socket.io.js script from the downloads page cdnjs.com link, the engine-io.js repository script linked is not working. docs are not helpful.

also client side

var socket = io(url)
socket.on('connect', function() { ... })

doesnt work, its too fast. socket = io(url).on('connect, function(){..})... works. docs are wrong.

docs are also wrong in a few spots using on('open') when 'connect' is the only event that works for me.

Was this page helpful?
0 / 5 - 0 ratings